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

next
ts 206 lines 8.6 KB
Raw
1 import { Config, Console, Effect, Option, Schema, Stdio, Stream } from 'effect';
2 import semver from 'semver';
3 import {
4 GitHub,
5 PositiveInt,
6 REPOSITORY_PATH,
7 RunId,
8 paginateArray,
9 request,
10 runUrl,
11 } from './github';
12 import { REGISTRY_VERSION } from './lanes';
13 import { packageLabel } from './release-pr';
14 import { appendFile, ensure, readJson, runMain } from './runtime';
15 import { BATCH_PATH, ReleaseBatch, channelOf } from './source';
16 import { DISPLAY, ReleaseState, STATUS_LABELS, Stage, describe, endsStage } from './state';
17
18 /** Status comments come from the workflow token, so nobody else's comment is ever edited. */
19 const STATUS_AUTHOR = 'github-actions[bot]';
20 const STATUS_MARKER = '<!-- sdk-release-status';
21 const marker = (stage: Stage) => `${STATUS_MARKER} stage=${stage} -->`;
22 const MARKED_STAGE = /^<!-- sdk-release-status stage=(request|review|publish) -->/;
23 const STAGE_ORDER = Stage.literals;
24
25 const IssueComment = Schema.Struct({
26 id: PositiveInt,
27 body: Schema.optionalKey(Schema.NullOr(Schema.String)),
28 user: Schema.NullOr(Schema.Struct({ login: Schema.String })),
29 });
30 const IssueLabel = Schema.Struct({ name: Schema.String });
31 const IssueState = Schema.Struct({ state: Schema.Literals(['open', 'closed']) });
32 const Written = Schema.Unknown;
33
34 /**
35 * Shows `state` on the request issue: one status comment edited in place, one status label, and
36 * the issue closed once the release can no longer advance. The comment records which stage wrote
37 * it, so a late or re-run earlier stage never replaces a later stage's result; nothing else is
38 * read back.
39 */
40 export const showStatus = (issue: number, state: ReleaseState, run: string, stage: Stage) =>
41 Effect.gen(function* () {
42 const display = DISPLAY[state._tag];
43 const body = `${marker(stage)}\n**SDK release: ${display.label.replace('sdk-release:', '')}**\n\n${describe(state)}\n\n<sub>Updated by ${runUrl(run)}</sub>`;
44 const issuePath = `${REPOSITORY_PATH}/issues/${issue}`;
45 const existing = yield* paginateArray(`${issuePath}/comments`, IssueComment).pipe(
46 Stream.filter(
47 comment =>
48 comment.user?.login === STATUS_AUTHOR && (comment.body ?? '').startsWith(STATUS_MARKER)
49 ),
50 Stream.runHead
51 );
52 const shown = Option.flatMap(existing, comment =>
53 Option.fromNullishOr(MARKED_STAGE.exec(comment.body ?? '')?.[1] as Stage | undefined)
54 );
55 const later = Option.filter(
56 shown,
57 shownStage => STAGE_ORDER.indexOf(shownStage) > STAGE_ORDER.indexOf(stage)
58 );
59 if (Option.isSome(later))
60 return yield* Console.log(`The ${later.value} stage already reported; keeping its status`);
61 yield* Option.match(existing, {
62 onSome: comment =>
63 request('PATCH', `${REPOSITORY_PATH}/issues/comments/${comment.id}`, Written, { body }),
64 onNone: () => request('POST', `${issuePath}/comments`, Written, { body }),
65 });
66 const labels = yield* Stream.runCollect(paginateArray(`${issuePath}/labels`, IssueLabel));
67 for (const { name } of labels.filter(
68 label => STATUS_LABELS.includes(label.name) && label.name !== display.label
69 ))
70 yield* request('DELETE', `${issuePath}/labels/${encodeURIComponent(name)}`, Written);
71 yield* request('POST', `${issuePath}/labels`, Written, { labels: [display.label] });
72 if (display.close)
73 yield* request('PATCH', issuePath, Written, { state: 'closed', state_reason: display.close });
74 // A release that can advance again, such as one re-gated after a refusal, reopens its issue.
75 else if ((yield* request('GET', issuePath, IssueState)).state === 'closed')
76 yield* request('PATCH', issuePath, Written, { state: 'open' });
77 });
78
79 /** A job's result as GitHub reports it to the jobs that need it. */
80 const JobResult = Schema.Literals(['success', 'failure', 'cancelled', 'skipped']);
81 const Results = Schema.Record(Schema.String, JobResult);
82
83 /**
84 * The state a stage ended in: `Failed` when any of its jobs failed or was cancelled, otherwise
85 * the state its last job recorded. The publish stage records nothing, because reaching the end
86 * with every job green is what `Published` means.
87 */
88 export const stageOutcome = <E, R>(
89 stage: Stage,
90 results: Readonly<Record<string, typeof JobResult.Type>>,
91 recorded: Option.Option<ReleaseState>,
92 published: Effect.Effect<ReleaseState, E, R>,
93 run: string
94 ) =>
95 Effect.gen(function* () {
96 const failed = Object.entries(results)
97 .filter(([, result]) => result === 'failure' || result === 'cancelled')
98 .map(([job]) => job);
99 const state = failed.length
100 ? ReleaseState.make({ _tag: 'Failed', stage, jobs: failed, run: runUrl(run) })
101 : yield* Option.match(recorded, { onSome: Effect.succeed, onNone: () => published });
102 yield* ensure(endsStage(stage, state), `The ${stage} stage cannot end in ${state._tag}`);
103 return state;
104 });
105
106 /** Every planned package and its new version, as the status comment lists them. */
107 const publishedState = (batch: ReleaseBatch) =>
108 ReleaseState.make({
109 _tag: 'Published',
110 versions: batch.plan.releases.map(release => ({
111 name: packageLabel(release.name),
112 version: REGISTRY_VERSION[release.language](release.newVersion),
113 })),
114 });
115
116 /**
117 * A job output the status job reads. GitHub passes an output that a failed or skipped job never
118 * wrote as an empty string, so empty means absent.
119 */
120 export const jobOutput = <A, E>(decode: (text: string) => Effect.Effect<A, E>, text: string) =>
121 text === '' ? Effect.succeedNone : Effect.asSome(decode(text));
122
123 export const StatusEnvironment = Config.all({
124 token: Config.schema(Schema.NonEmptyString, 'GITHUB_TOKEN'),
125 runId: Config.schema(RunId, 'GITHUB_RUN_ID'),
126 summaryPath: Config.String('GITHUB_STEP_SUMMARY'),
127 results: Config.schema(Schema.fromJsonString(Results), 'RESULTS'),
128 outcome: Config.String('OUTCOME').pipe(Config.withDefault('')),
129 issue: Config.String('ISSUE').pipe(Config.withDefault('')),
130 });
131
132 /**
133 * `report.ts status <stage>` runs last in every stage, even after a failure or cancellation. It
134 * writes the outcome to the run summary and shows it on the request issue when there is one.
135 */
136 const statusMode = (stage: Stage) =>
137 Effect.gen(function* () {
138 const env = yield* StatusEnvironment;
139 const issue = yield* jobOutput(
140 Schema.decodeUnknownEffect(Schema.NumberFromString.check(Schema.isInt())),
141 env.issue
142 );
143 const state = yield* stageOutcome(
144 stage,
145 env.results,
146 yield* jobOutput(
147 Schema.decodeUnknownEffect(Schema.fromJsonString(ReleaseState)),
148 env.outcome
149 ),
150 Effect.map(readJson(ReleaseBatch, BATCH_PATH), publishedState),
151 env.runId
152 );
153 yield* appendFile(env.summaryPath, `${describe(state)}\n`);
154 yield* Option.match(issue, {
155 onNone: () => Console.log('No request issue to update'),
156 onSome: issue =>
157 showStatus(issue, state, env.runId, stage).pipe(Effect.provide(GitHub.layer(env.token))),
158 });
159 });
160
161 /**
162 * The `name@version` specs that move the docs to the released npm versions. Packages the docs do
163 * not use, and pins already at or past the release (an older release's retry), are left alone.
164 */
165 export const docsPinSpecs = (
166 released: Readonly<Record<string, string>>,
167 devDependencies: Readonly<Record<string, string>>
168 ) =>
169 Object.entries(released)
170 .filter(([name, version]) => {
171 const pinned = semver.minVersion(devDependencies[name] ?? '');
172 return name in devDependencies && (pinned === null || semver.gt(version, pinned));
173 })
174 .map(([name, version]) => `${name}@${version}`);
175
176 const DocsManifest = Schema.Struct({
177 devDependencies: Schema.Record(Schema.String, Schema.String),
178 });
179
180 /**
181 * `report.ts docs-pins <docs package.json>` prints the `bun add` specs for this tag's npm
182 * release. A beta prints nothing: the docs follow stable releases only.
183 */
184 const docsPinsMode = (manifestPath: string) =>
185 Effect.gen(function* () {
186 const batch = yield* readJson(ReleaseBatch, BATCH_PATH);
187 const released = Object.fromEntries(
188 batch.plan.releases
189 .filter(release => channelOf(batch).pinsDocs && release.language === 'typescript')
190 .map(release => [release.name, release.newVersion])
191 );
192 const { devDependencies } = yield* readJson(DocsManifest, manifestPath);
193 yield* Console.log(docsPinSpecs(released, devDependencies).join(' '));
194 });
195
196 const Arguments = Schema.Union([
197 Schema.Tuple([Schema.Literal('status'), Stage]),
198 Schema.Tuple([Schema.Literal('docs-pins'), Schema.String]),
199 ]);
200
201 const main = Effect.gen(function* () {
202 const args = yield* Schema.decodeUnknownEffect(Arguments)(yield* (yield* Stdio.Stdio).args);
203 yield* args[0] === 'status' ? statusMode(args[1]) : docsPinsMode(args[1]);
204 });
205
206 if (import.meta.main) runMain(main);