Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

generate-release-notes.ts

370 lines15.1 KB

1#!/usr/bin/env node
2​
3import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
4import * as NodeServices from "@effect/platform-node/NodeServices";
5import * as Config from "effect/Config";
6import * as Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as Logger from "effect/Logger";
10import * as Option from "effect/Option";
11import * as Schema from "effect/Schema";
12import { Command, Flag } from "effect/cli";
13import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
14import { ChildProcess, ChildProcessSpawner } from "effect/process";
15​
16// Release notes cover web, desktop, and server. Mobile ships its own store notes.
17const MOBILE_SCOPES = new Set(["mobile", "android", "ios"]);
18const COMMIT_SCOPES = /^[a-z]+\(([^)]*)\)!?:/i;
19const PULL_REQUEST_NUMBER = /\(#(\d+)\)$/;
20const PULL_REQUEST_BODY_LIMIT = 300;
21const SUMMARY_MODEL = "gpt-6.1-terra";
22​
23const SUMMARY_INSTRUCTIONS = `You write release notes for T3 Code, a GUI for coding agents (web and desktop apps backed by a server; providers like Codex, Claude, Cursor, OpenCode).
24​
25These notes cover the web app, desktop app, and server only. The mobile app has its own release notes, so leave out anything only about mobile, iOS, or Android.
26​
27You get the commit subjects merged since the last release, oldest first. Most end with a PR number like (#1234). Each commit shows lines added and removed and files changed, then a trimmed PR description on the next line starting with ">". Use the descriptions to understand what changed for users and why it matters. Line counts hint at size, but a small change can still matter most.
28​
29Output Markdown in exactly this shape and nothing else:
30​
31## Highlights
32Up to 4 short sentences. Name only the new features a user would care about most. If no new feature matters to users, write one sentence about the most important fix. Each feature gets a few words that make the benefit clear, not a description of how it works or where the button is.
33​
34## Fixes
35- Up to 10 bullets, one fix each, under 10 words, ending with the PR number like (#123). Fewer is fine. Never pad.
36- Each bullet names what was broken and says it works now. A user who hit the bug should recognize it.
37- Only list fixes from fix commits. New abilities go in Highlights or nowhere. Say "again" only if the commit says it.
38​
39How to write:
40- Pick only significant, user-facing changes. Leave out visual polish (focus rings, spacing, colors), layout tweaks, refactors, tests, CI, build, docs, deps, internal tooling, and performance or efficiency work a user would not feel.
41- Include Labs and beta features, with "(beta)" after the feature. Leave out work marked internal testing or dev-only.
42- Describe each feature as it is at the end of the range. If a beta feature became standard later in the range, it is not beta.
43- Say what the user gets, as short as possible. Cut details, conditions, and mechanics.
44- No defaults or rollout state ("on by default", "now available", "behind a flag").
45- For lists of file types or formats, use common extensions: "previews for .docx, .ttf, .sqlite, .zip and more".
46- No internal names, env vars, file paths, or code terms.
47- No em dashes. No hype words. Do not invent anything that is not in the input.
48​
49Examples of the tone:
50- Bad: "Cmd+K now finds the right thread first, and it searches message text too." Good: "Much better Cmd+K search."
51- Bad: "You can share a thread with a guest who watches it live and sends messages that you approve." Good: "Share threads with guests, safely."
52- Bad: "Triage issues from the command palette." Good: "Fix and debug T3 Code itself with a new 'triage' command."
53- Bad: "Settings and Usage open as large modals over your thread." Good: leave it out.
54- Bad: "Cmd/Ctrl+W closes tabs safely (#25860)" Good: "Cmd/Ctrl+W no longer closes the whole window (#25860)"`;
55​
56class EmptyReleaseRangeError extends Schema.TaggedError<EmptyReleaseRangeError>()(
57 "EmptyReleaseRangeError",
58 { range: Schema.String },
59) {}
60​
61interface ReleaseCommit {
62 readonly subject: string;
63 readonly authorName: string;
65​
66const PullRequest = Schema.Struct({
67 body: Schema.String,
68 additions: Schema.Number,
69 deletions: Schema.Number,
70 changedFiles: Schema.Number,
71 author: Schema.NullOr(
72 Schema.Struct({
73 __typename: Schema.String,
74 login: Schema.String,
75 name: Schema.optional(Schema.NullOr(Schema.String)),
76 }),
77 ),
78});
79export type PullRequest = typeof PullRequest.Type;
80​
81const PullRequestQueryResponse = Schema.Struct({
82 data: Schema.Struct({
83 repository: Schema.Record(Schema.String, Schema.NullOr(PullRequest)),
84 }),
85});
86​
87const GeneratedNotes = Schema.Struct({ body: Schema.String });
88​
89const SummaryResponse = Schema.Struct({
90 status: Schema.String,
91 output: Schema.Array(
92 Schema.Struct({
93 type: Schema.String,
94 content: Schema.optional(
95 Schema.Array(Schema.Struct({ type: Schema.String, text: Schema.optional(Schema.String) })),
96 ),
97 }),
98 ),
99 usage: Schema.optional(
100 Schema.Struct({ input_tokens: Schema.Number, output_tokens: Schema.Number }),
101 ),
102});
103​
104const pullRequestNumber = (subject: string) => {
105 const match = PULL_REQUEST_NUMBER.exec(subject);
106 return match ? Number(match[1]) : undefined;
107};
108​
109/** Drops a commit only when every scope is mobile, so `fix(web,mobile)` stays. */
110export function isReleaseNoteCommit(commit: ReleaseCommit): boolean {
111 const scopes = COMMIT_SCOPES.exec(commit.subject)?.[1]?.split(",");
112 return !scopes?.every((scope) => MOBILE_SCOPES.has(scope.trim().toLowerCase()));
114​
115/** Keeps the prose of a PR body: no images, tables, headings, HTML, or verification sections. */
116function trimPullRequestBody(body: string, limit = PULL_REQUEST_BODY_LIMIT): string {
117 const [prose = ""] = body.split(/\n#+\s*(?:Verification|Council|Test|Testing|Screenshots)\b/i);
118 const text = prose
119 .split("\n")
120 .filter((line) => line.trim() !== "" && !/^\s*[!|#<]/.test(line))
121 .join(" ")
122 .replace(/\s+/g, " ")
123 .trim();
124 return text.length > limit ? `${text.slice(0, limit)}...` : text;
126​
127function buildSummaryInput(
128 commits: ReadonlyArray<ReleaseCommit>,
129 pullRequests: ReadonlyMap<number, PullRequest>,
130): string {
131 return commits
132 .flatMap(({ subject }) => {
133 const number = pullRequestNumber(subject);
134 const pullRequest = number === undefined ? undefined : pullRequests.get(number);
135 if (!pullRequest) return [subject];
136 const line = `${subject} [+${pullRequest.additions} -${pullRequest.deletions}, ${pullRequest.changedFiles} files]`;
137 const body = trimPullRequestBody(pullRequest.body);
138 return body ? [line, ` > ${body}`] : [line];
139 })
140 .join("\n");
142​
143/** PR authors without bots, plus authors of direct pushes who have no PR in the range. */
144export function countContributors(
145 commits: ReadonlyArray<ReleaseCommit>,
146 pullRequests: ReadonlyMap<number, PullRequest>,
147): number {
148 const people = new Set<string>();
149 // A PR's squash commit carries its author's git name, which may differ from the profile name.
150 const prAuthorNames = new Set<string>();
151 const directAuthors: string[] = [];
152 for (const commit of commits) {
153 const number = pullRequestNumber(commit.subject);
154 const author = number === undefined ? undefined : pullRequests.get(number)?.author;
155 if (!author) {
156 directAuthors.push(commit.authorName);
157 continue;
158 }
159 if (author.__typename === "Bot" || author.login.endsWith("[bot]")) continue;
160 people.add(author.login);
161 prAuthorNames.add(commit.authorName);
162 if (author.name) prAuthorNames.add(author.name);
163 }
164 for (const name of directAuthors) {
165 if (!name.endsWith("[bot]") && !prAuthorNames.has(name)) people.add(name);
166 }
167 return people.size;
169​
170/** No date here: the app shows how long ago a release shipped, and GitHub shows the date. */
171function buildReleaseHeader(version: string, changes: number, contributors: number): string {
172 const plural = (count: number, word: string) => `${count} ${word}${count === 1 ? "" : "s"}`;
173 return `**v${version.replace(/^v/, "")}** · ${plural(changes, "change")} from ${plural(contributors, "contributor")}`;
175​
176/** The summary leads; GitHub's full list folds under it. Clients cut the body at `<details>`. */
177function assembleReleaseNotes(header: string, summary: string, fullChangelog: string): string {
178 return `${header}\n\n${summary.trim()}\n\n<details>\n<summary>Full changelog</summary>\n\n${fullChangelog.trim()}\n\n</details>\n`;
180​
181const run = Effect.fn("generateReleaseNotes.run")(function* (
182 command: string,
183 args: ReadonlyArray<string>,
184) {
185 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
186 return yield* spawner.string(ChildProcess.make(command, args));
187});
188​
189const decodeJson = <S extends Schema.Top>(schema: S) =>
190 Schema.decodeUnknownEffect(Schema.fromJsonString(schema));
191​
192const readCommits = Effect.fn("generateReleaseNotes.readCommits")(function* (
193 previousTag: string,
194 ref: string,
195) {
196 const log = yield* run("git", [
197 "log",
198 "--reverse",
199 "--format=%s%x1f%an",
200 `${previousTag}..${ref}`,
201 ]);
202 return log
203 .split("\n")
204 .filter((line) => line !== "")
205 .map((line): ReleaseCommit => {
206 const [subject = "", authorName = ""] = line.split("\x1f");
207 return { subject, authorName };
208 });
209});
210​
211const readPullRequests = Effect.fn("generateReleaseNotes.readPullRequests")(function* (
212 repository: string,
213 numbers: ReadonlyArray<number>,
214) {
215 const [owner, name] = repository.split("/");
216 const pullRequests = new Map<number, PullRequest>();
217 for (let start = 0; start < numbers.length; start += 100) {
218 const fields = numbers
219 .slice(start, start + 100)
220 .map(
221 (number) =>
222 `pr${number}: pullRequest(number: ${number}) { body additions deletions changedFiles author { __typename login ... on User { name } } }`,
223 )
224 .join("\n");
225 const query = `query($owner: String!, $name: String!) { repository(owner: $owner, name: $name) { ${fields} } }`;
226 const response = yield* decodeJson(PullRequestQueryResponse)(
227 yield* run("gh", [
228 "api",
229 "graphql",
230 "-f",
231 `query=${query}`,
232 "-f",
233 `owner=${owner}`,
234 "-f",
235 `name=${name}`,
236 ]),
237 );
238 for (const [alias, pullRequest] of Object.entries(response.data.repository)) {
239 if (pullRequest) pullRequests.set(Number(alias.slice(2)), pullRequest);
240 }
241 }
242 return pullRequests;
243});
244​
245const readFullChangelog = Effect.fn("generateReleaseNotes.readFullChangelog")(function* (options: {
246 readonly repository: string;
247 readonly tag: string;
248 readonly ref: string;
249 readonly previousTag: string;
250}) {
251 const response = yield* run("gh", [
252 "api",
253 `repos/${options.repository}/releases/generate-notes`,
254 "-f",
255 `tag_name=${options.tag}`,
256 "-f",
257 `target_commitish=${options.ref}`,
258 "-f",
259 `previous_tag_name=${options.previousTag}`,
260 ]);
261 return (yield* decodeJson(GeneratedNotes)(response)).body;
262});
263​
264export function summaryText(response: typeof SummaryResponse.Type): Option.Option<string> {
265 // An incomplete response can carry partial text; publishing it would cut the notes short.
266 if (response.status !== "completed") return Option.none();
267 const text = response.output
268 .flatMap((item) => item.content ?? [])
269 .flatMap((part) => (part.type === "output_text" && part.text ? [part.text] : []))
270 .join("")
271 .trim();
272 return text === "" ? Option.none() : Option.some(text);
274​
275const summarize = Effect.fn("generateReleaseNotes.summarize")(function* (input: string) {
276 const apiKey = yield* Config.Redacted("OPENAI_API_KEY");
277 const httpClient = yield* HttpClient.HttpClient;
278 const response = yield* HttpClientRequest.post("https://api.openai.com/v1/responses").pipe(
279 HttpClientRequest.bearerToken(apiKey),
280 HttpClientRequest.bodyJson({
281 model: SUMMARY_MODEL,
282 reasoning: { effort: "low" },
283 instructions: SUMMARY_INSTRUCTIONS,
284 input: `Commits:\n${input}`,
285 }),
286 Effect.flatMap(httpClient.execute),
287 Effect.flatMap(HttpClientResponse.filterStatusOk),
288 Effect.flatMap((response) => response.json),
289 Effect.flatMap(Schema.decodeUnknownEffect(SummaryResponse)),
290 Effect.timeout("3 minutes"),
291 );
292 yield* Effect.logInfo("release summary generated").pipe(
293 Effect.annotateLogs({
294 model: SUMMARY_MODEL,
295 inputTokens: response.usage?.input_tokens,
296 outputTokens: response.usage?.output_tokens,
297 }),
298 );
299 return summaryText(response);
300});
301​
302const command = Command.make(
303 "generate-release-notes",
304 {
305 repository: Flag.String("repository").pipe(Flag.withDescription("GitHub owner/name.")),
306 tag: Flag.String("tag").pipe(Flag.withDescription("Tag being released.")),
307 ref: Flag.String("ref").pipe(Flag.withDescription("Commit being released.")),
308 previousTag: Flag.String("previous-tag").pipe(Flag.withDescription("Previous release tag.")),
309 version: Flag.String("version").pipe(Flag.withDescription("Version shown in the header.")),
310 output: Flag.String("output").pipe(Flag.withDescription("File to write the notes to.")),
311 },
312 ({ repository, tag, ref, previousTag, version, output }) =>
313 Effect.gen(function* () {
314 // The header counts every commit in the range; the summary skips mobile-only work.
315 const allCommits = yield* readCommits(previousTag, ref);
316 // The spawner ignores exit codes, so a failed git log shows up as an empty range.
317 if (allCommits.length === 0) {
318 return yield* new EmptyReleaseRangeError({ range: `${previousTag}..${ref}` });
319 }
320 const commits = allCommits.filter(isReleaseNoteCommit);
321 const numbers = [
322 ...new Set(allCommits.flatMap(({ subject }) => pullRequestNumber(subject) ?? [])),
323 ];
324 const [pullRequests, fullChangelog] = yield* Effect.all(
325 [
326 readPullRequests(repository, numbers),
327 readFullChangelog({ repository, tag, ref, previousTag }),
328 ],
329 { concurrency: "unbounded" },
330 );
331 const header = buildReleaseHeader(
332 version,
333 allCommits.length,
334 countContributors(allCommits, pullRequests),
335 );
336 // With no summary, write nothing: the release falls back to GitHub's generated notes.
337 const summary =
338 commits.length === 0
339 ? Option.none<string>()
340 : yield* summarize(buildSummaryInput(commits, pullRequests));
341 if (Option.isNone(summary)) {
342 return yield* Effect.logWarning("no release summary, leaving GitHub's notes in place");
343 }
344 const fs = yield* FileSystem.FileSystem;
345 // Publish uses the file when it exists, so a partial write must never land at `output`.
346 yield* fs.writeFileString(
347 `${output}.tmp`,
348 assembleReleaseNotes(header, summary.value, fullChangelog),
349 );
350 yield* fs.rename(`${output}.tmp`, output);
351 yield* Effect.logInfo("release notes written").pipe(
352 Effect.annotateLogs({ output, commits: commits.length }),
353 );
354 }),
355).pipe(
356 Command.withDescription("Write release notes with a model summary over GitHub's full list."),
357);
358​
359if (import.meta.main) {
360 Command.run(command, { version: "0.0.0" }).pipe(
361 Effect.provide(
362 Layer.mergeAll(
363 Logger.layer([Logger.consolePretty()]),
364 NodeServices.layer,
365 FetchHttpClient.layer,
366 ),
367 ),
368 NodeRuntime.runMain,
369 );