diff --git a/.githooks/commit-msg b/.githooks/commit-msg new file mode 100755 index 0000000..951f800 --- /dev/null +++ b/.githooks/commit-msg @@ -0,0 +1,3 @@ +#!/bin/sh +# Check the message against Conventional Commits (ADR 31). Enable: git config core.hooksPath .githooks +exec node scripts/check-commits.ts --file "$1" diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 30c8045..5f44d5b 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -11,6 +11,9 @@ updates: default-days: 1 versioning-strategy: increase # keep exact pins (saveExact) open-pull-requests-limit: 5 + commit-message: # Conventional Commits (ADR 31): "build(deps): bump …", "build(deps-dev): bump …" + prefix: build + include: scope ignore: # rolldown is pinned to the version Vite resolves (scripts/dependencies.test.ts); it moves with Vite. - dependency-name: rolldown @@ -30,6 +33,9 @@ updates: day: monday cooldown: default-days: 1 + commit-message: + prefix: ci + include: scope groups: actions: patterns: ["*"] diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 97af615..02830bf 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -13,6 +13,27 @@ concurrency: cancel-in-progress: true jobs: + commits: + name: Commit messages + if: github.event_name == 'pull_request' + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + persist-credentials: false + + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 22 + + # Every commit of the pull request, so release-please reads each one when it is merged (ADR 31). + - run: node scripts/check-commits.ts "$BASE..$HEAD" + env: + BASE: ${{ github.event.pull_request.base.sha }} + HEAD: ${{ github.event.pull_request.head.sha }} + check: name: pnpm ${{ matrix.check }} (${{ matrix.runtime }}) runs-on: ubuntu-latest diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 23cb000..dec3e4b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,10 +1,13 @@ name: Release -# On a tag v (the root package.json's version): check, build and publish the plugin (ADR 30). +# On a push to main, release-please keeps a release PR open: the next version and its changelog (ADR 31). When that +# PR is merged, it tags v and creates the GitHub Release; then, as on a tag pushed by hand (ADR 30): # build: pnpm check (the no-egress guard included), the smoke test, dist/plugin, a tarball and the SBOMs. -# attest: build provenance for the tarball. publish: the plugin branch and the GitHub Release. +# attest: build provenance for the tarball. publish: the plugin branch and the release's files. +# release-please's tag starts no workflow (GITHUB_TOKEN), so the build runs in this one. on: push: + branches: [main] tags: ["v*"] permissions: @@ -15,15 +18,39 @@ concurrency: cancel-in-progress: false jobs: + release-please: + name: Release PR + if: github.ref_type == 'branch' + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + contents: write # the release branch, the tag and the GitHub Release + pull-requests: write # open and update the release PR + issues: write # the release PR's labels + outputs: + created: ${{ steps.release.outputs.release_created }} + tag: ${{ steps.release.outputs.tag_name }} + steps: + - id: release + uses: googleapis/release-please-action@45996ed1f6d02564a971a2fa1b5860e934307cf7 # v5.0.0 + with: + config-file: release-please-config.json + manifest-file: .release-please-manifest.json + build: name: Check and build + needs: release-please + # On a tag push the release-please job is skipped; !failure() lets this job run then. + if: ${{ !failure() && !cancelled() && (github.ref_type == 'tag' || needs.release-please.outputs.created == 'true') }} runs-on: ubuntu-latest timeout-minutes: 20 outputs: + tag: ${{ steps.version.outputs.tag }} version: ${{ steps.version.outputs.version }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: + ref: ${{ needs.release-please.outputs.tag || github.ref_name }} fetch-depth: 0 # gitleaks scans the full history persist-credentials: false @@ -37,9 +64,10 @@ jobs: - id: version run: | node scripts/release.ts check-tag "$TAG" + echo "tag=$TAG" >> "$GITHUB_OUTPUT" echo "version=${TAG#v}" >> "$GITHUB_OUTPUT" env: - TAG: ${{ github.ref_name }} + TAG: ${{ needs.release-please.outputs.tag || github.ref_name }} - run: pnpm install --frozen-lockfile @@ -69,6 +97,7 @@ jobs: attest: name: Build provenance needs: build + if: ${{ !failure() && !cancelled() && needs.build.result == 'success' }} runs-on: ubuntu-latest timeout-minutes: 5 permissions: @@ -89,6 +118,7 @@ jobs: publish: name: Plugin branch and GitHub Release needs: [build, attest] + if: ${{ !failure() && !cancelled() && needs.attest.result == 'success' }} runs-on: ubuntu-latest timeout-minutes: 5 permissions: @@ -97,6 +127,7 @@ jobs: # The one job that pushes, so the only one that keeps the token in git's config. - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: + ref: ${{ needs.build.outputs.tag }} persist-credentials: true - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 @@ -118,7 +149,7 @@ jobs: found=0; git ls-remote --exit-code --heads origin plugin > /dev/null || found=$? if [ "$found" = 0 ]; then git fetch --no-tags origin "+refs/heads/plugin:refs/remotes/origin/plugin"; elif [ "$found" != 2 ]; then exit "$found"; fi - sha=$(node scripts/release.ts commit-plugin unpacked/plugin refs/remotes/origin/plugin "$GITHUB_SHA") + sha=$(node scripts/release.ts commit-plugin unpacked/plugin refs/remotes/origin/plugin "$(git rev-parse HEAD)") git push origin "$sha:refs/heads/plugin" env: VERSION: ${{ needs.build.outputs.version }} @@ -127,11 +158,19 @@ jobs: GIT_COMMITTER_NAME: github-actions[bot] GIT_COMMITTER_EMAIL: 41898282+github-actions[bot]@users.noreply.github.com - - name: Create the GitHub Release + # release-please created the release with the changelog as its notes; a tag pushed by hand has none yet. + - name: The GitHub Release's files and notes run: | - gh release create "$TAG" out/* --verify-tag --title "Quantext $VERSION" --generate-notes \ - --notes "Install: \`claude plugin marketplace add $GITHUB_REPOSITORY\`, then \`claude plugin install quantext@quantext\`. Verify the tarball: \`gh attestation verify quantext-plugin-$VERSION.tar.gz --repo $GITHUB_REPOSITORY\`." + install="Install: \`claude plugin marketplace add $GITHUB_REPOSITORY\`, then \`claude plugin install quantext@quantext\`. Verify the tarball: \`gh attestation verify quantext-plugin-$VERSION.tar.gz --repo $GITHUB_REPOSITORY\`." + if gh release view "$TAG" > /dev/null; then + gh release upload "$TAG" out/* + gh release edit "$TAG" --title "Quantext $VERSION" --notes "$(gh release view "$TAG" --json body --jq .body) + + $install" + else + gh release create "$TAG" out/* --verify-tag --title "Quantext $VERSION" --generate-notes --notes "$install" + fi env: GH_TOKEN: ${{ github.token }} - TAG: ${{ github.ref_name }} + TAG: ${{ needs.build.outputs.tag }} VERSION: ${{ needs.build.outputs.version }} diff --git a/.release-please-manifest.json b/.release-please-manifest.json new file mode 100644 index 0000000..9d957c7 --- /dev/null +++ b/.release-please-manifest.json @@ -0,0 +1 @@ +{ ".": "0.1.0" } diff --git a/AGENTS.md b/AGENTS.md index 006df08..b274055 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -40,7 +40,15 @@ quality bar. Decisions that are hard to change are recorded in `docs/adr/`. ## Commits - One logical change per commit. No co-author lines. -- **Subject:** imperative, about 50 characters, at most 72, no period at the end. It says *what* changed. +- **Subject:** [Conventional Commits](https://www.conventionalcommits.org/): `(): `, scope + optional. Then imperative, lower case, about 50 characters, at most 72 in all, no period at the end. It says + *what* changed. release-please reads the types to pick the next version and write the changelog (ADR 31): + - `feat` (a new user-visible feature, minor bump) and `fix` (a user-visible bug fix, patch bump) go in the + changelog. A fix to work that is not released yet is not a `fix`: use the type of the work it corrects. + - `perf`, `refactor`, `docs`, `test`, `build`, `ci`, `chore`, `revert` for the rest. + - `!` after the type (`feat!:`), or a `BREAKING CHANGE:` footer, marks a breaking change. + - CI checks every commit of a pull request (`scripts/check-commits.ts`). Check yours before you push, because + pushed commits are not rewritten: `git config core.hooksPath .githooks` turns on the `commit-msg` hook. - **Body:** after one blank line, wrapped at 72. It says *why*, and anything a reviewer would not see in the diff (a trade-off, a rejected option, a link to an ADR or a known issue). Leave it out only for trivial commits. - **Size:** keep a commit reviewable, as a rule under ~400 changed lines (lockfiles and recorded fixtures do not diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index acd5049..36cbcd2 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -171,7 +171,8 @@ docs/ this file, the store schema (schema.md), decision records (docs/adr The release is one plugin folder, `dist/plugin/` from `pnpm build:plugin`: the mod, the bundled engine and the built viewer (ADR 27). A tag `v` publishes it to the `plugin` branch, which the marketplace entry names, and to a -GitHub Release; the root `package.json` holds the one version (ADR 30). +GitHub Release; the root `package.json` holds the one version (ADR 30). release-please keeps a release PR open with +the next version and changelog, from the Conventional Commits on `main`; merging it tags and publishes (ADR 31). ## Quality bar diff --git a/docs/adr/0030-release-to-a-plugin-branch.md b/docs/adr/0030-release-to-a-plugin-branch.md index 5040e9e..49ee779 100644 --- a/docs/adr/0030-release-to-a-plugin-branch.md +++ b/docs/adr/0030-release-to-a-plugin-branch.md @@ -1,6 +1,6 @@ # 30. Releases publish the built plugin to a `plugin` branch; one version, in the root package.json -Status: accepted +Status: accepted (amended by ADR 31: release-please makes the version bump, the tag and the release) ## Context @@ -65,7 +65,7 @@ Options considered: `claude plugin install quantext@quantext` fails at fetch. Development installs use `quantext-dev`. - A developer who added the repo folder as marketplace `quantext` (ADR 27) now gets the GitHub source from it; they remove it and add `./dist` instead. -- To release: bump the root version, merge, tag `v` on `main` and push the tag. A tag that does not match +- To release (before ADR 31): bump the root version, merge, tag `v` on `main` and push the tag. A tag that does not match the version fails the first step. Users update with `claude plugin update quantext@quantext`. - The branch is not protected by a review: anyone with push access could write it. A ruleset that lets only GitHub Actions push `plugin` would close that. diff --git a/docs/adr/0031-conventional-commits-and-release-please.md b/docs/adr/0031-conventional-commits-and-release-please.md new file mode 100644 index 0000000..99a301d --- /dev/null +++ b/docs/adr/0031-conventional-commits-and-release-please.md @@ -0,0 +1,43 @@ +# 31. Conventional Commits, and release-please makes the release PR + +Status: accepted + +## Context + +A release (ADR 30) was manual: bump the root version, merge, tag, push the tag, and the release notes came from +the PR titles. We want the version, the changelog and the tag made for us, and a person still to decide when to +release. + +Options considered: + +- **Manual tag with generated notes.** No new parts, but the version and the changelog stay manual. +- **semantic-release.** Releases on every merge with a `feat` or `fix`: no human gate. +- **Changesets.** Plain commit subjects stay, but every PR adds a `.changeset/*.md` file, and it is a dev dependency. +- **release-please.** A bot keeps one release PR open with the next version and `CHANGELOG.md`; merging it tags and + creates the GitHub Release. It reads Conventional Commits, so the commit style changes. Chosen. + +## Decision + +- **Commits** follow Conventional Commits (`AGENTS.md`): `feat` is a minor bump, `fix` a patch, `!` or a + `BREAKING CHANGE:` footer a major one. Before 1.0 a breaking change bumps the minor (`bump-minor-pre-major`). +- **The check** is `scripts/check-commits.ts` (subject rules in `scripts/lib/commit-message.ts`), not commitlint, + which would add many dependencies for a few rules. The `commits` job in `ci.yml` checks every commit of a pull + request except merges; `.githooks/commit-msg` checks one before it is pushed. Dependabot writes `build(deps)` and + `ci(deps)` subjects. +- **release-please** (`release-please-config.json`, `.release-please-manifest.json`, release type `node`, tags + `v`) runs as the first job of `release.yml` on each push to `main`, with `GITHUB_TOKEN` only. It writes + the root `package.json` version, so ADR 30's one version stays. A tag made with `GITHUB_TOKEN` starts no other + workflow, so the build, attest and publish jobs run in the same workflow when it reports a release. The publish + job adds the files and the install notes to the release that release-please created. A tag pushed by hand still + releases as before. +- **Permissions.** The release-please job writes contents, pull requests and issues (labels); the publish job + writes contents. `scripts/workflows.test.ts` checks that no other job writes. + +## Consequences + +- The repo setting "Allow GitHub Actions to create and approve pull requests" must be on. +- A PR that `GITHUB_TOKEN` opens starts no workflow, so CI does not run on the release PR. It changes only the + version, the changelog and the manifest, and the release build runs `pnpm check` before it publishes. +- With merge commits, each commit of a merged PR is one changelog line. Review fixes to unreleased work take the + type of the work they correct, not `fix`. +- Commits before this ADR are not Conventional Commits, so the first changelog leaves them out. diff --git a/release-please-config.json b/release-please-config.json new file mode 100644 index 0000000..6f6a8ea --- /dev/null +++ b/release-please-config.json @@ -0,0 +1,11 @@ +{ + "$schema": "https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json", + "packages": { + ".": { + "release-type": "node", + "include-component-in-tag": false, + "bump-minor-pre-major": true, + "changelog-path": "CHANGELOG.md" + } + } +} diff --git a/scripts/check-commits.ts b/scripts/check-commits.ts new file mode 100644 index 0000000..9c52703 --- /dev/null +++ b/scripts/check-commits.ts @@ -0,0 +1,39 @@ +/** + * Check commit messages against Conventional Commits (ADR 31). + * `check-commits.ts ..`: every commit in the range but merges (CI, on a pull request). + * `check-commits.ts --file `: one message file (the `.githooks/commit-msg` hook). + */ +import { execFileSync } from "node:child_process"; +import { readFileSync } from "node:fs"; +import { checkCommitMessage } from "./lib/commit-message.ts"; + +const [first = "", second] = process.argv.slice(2); +let messages: { name: string; text: string }[]; +if (first === "--file" && second) { + messages = [{ name: second, text: readFileSync(second, "utf8") }]; +} else if (first.includes("..") && second === undefined) { + const log = execFileSync("git", ["log", "--no-merges", "--format=%h %s%x00%B%x1e", first], { encoding: "utf8" }); + messages = log + .split("\x1e") + .filter((entry) => entry.trim() !== "") + .map((entry) => { + const [name = "", text = ""] = entry.trim().split("\0"); + return { name, text }; + }); +} else { + console.error("usage: check-commits.ts .. | --file "); + process.exit(2); +} + +let bad = 0; +for (const { name, text } of messages) { + const problems = checkCommitMessage(text); + if (problems.length === 0) continue; + bad++; + console.error(`${name}\n${problems.map((p) => ` - ${p}`).join("\n")}`); +} +if (bad > 0) { + console.error(`\n${bad} of ${messages.length} commit message(s) do not follow Conventional Commits (AGENTS.md).`); + process.exit(1); +} +console.log(`${messages.length} commit message(s) follow Conventional Commits`); diff --git a/scripts/lib/commit-message.test.ts b/scripts/lib/commit-message.test.ts new file mode 100644 index 0000000..7018d0f --- /dev/null +++ b/scripts/lib/commit-message.test.ts @@ -0,0 +1,31 @@ +import { describe, expect, test } from "vitest"; +import { checkCommitMessage } from "./commit-message.ts"; + +describe("checkCommitMessage", () => { + test.each([ + "fix: name the reason when the mod says the cache broke", + "feat(viewer): show the unlogged estimate beside the session cost", + "feat!: drop the v0 API", + "build(deps): bump vite from 7.1.0 to 7.1.1", + "chore(main): release 0.2.0", + "fix: end a stuck engine\n\nThe old exit left the port bound.\n", + "fix: read only regular files\n# a git comment line\n", + ])("accepts %j", (message) => { + expect(checkCommitMessage(message)).toEqual([]); + }); + + test.each([ + ["Name the reason when the mod says the cache broke", /type/], + ["fixes: wrong type", /type/], + ["fix:no space", /type/], + ["fix(Viewer): upper-case scope", /type/], + ["fix: ends with a period.", /period/], + [`fix: ${"x".repeat(70)}`, /72/], + ["fix: subject\nbody without a blank line", /blank/], + ["", /empty/], + ])("rejects %j", (message, reason) => { + const problems = checkCommitMessage(message); + expect(problems.length).toBeGreaterThan(0); + expect(problems.join("\n")).toMatch(reason); + }); +}); diff --git a/scripts/lib/commit-message.ts b/scripts/lib/commit-message.ts new file mode 100644 index 0000000..a4cea41 --- /dev/null +++ b/scripts/lib/commit-message.ts @@ -0,0 +1,25 @@ +/** Commit messages follow Conventional Commits, so release-please can pick the next version (ADR 31). */ + +export const COMMIT_TYPES = ["feat", "fix", "perf", "refactor", "docs", "test", "build", "ci", "chore", "revert"]; + +const HEADER = new RegExp(`^(?:${COMMIT_TYPES.join("|")})(?:\\([a-z0-9-]+\\))?!?: \\S`); + +/** + * The problems with one commit message, empty when it is fine. Lines that start with `#` are git's + * comments and do not count. Checks the subject (type, optional scope, `!`, at most 72 characters, no + * final period) and the blank line after it; the body is free text. + */ +export function checkCommitMessage(message: string): string[] { + const lines = message.split("\n").filter((line) => !line.startsWith("#")); + const subject = lines[0]?.trim() ?? ""; + if (subject === "") return ["the message is empty"]; + const problems: string[] = []; + if (!HEADER.test(subject)) + problems.push( + `the subject must start with ": " or "(): ", type one of ${COMMIT_TYPES.join(", ")}`, + ); + if (subject.length > 72) problems.push(`the subject has ${subject.length} characters, at most 72`); + if (subject.endsWith(".")) problems.push("the subject ends with a period"); + if ((lines[1] ?? "").trim() !== "") problems.push("the second line must be blank"); + return problems; +} diff --git a/scripts/workflows.test.ts b/scripts/workflows.test.ts index 89d1a2b..f83a190 100644 --- a/scripts/workflows.test.ts +++ b/scripts/workflows.test.ts @@ -20,13 +20,18 @@ describe("workflows", () => { } }); - test("only the release's publish job may write contents; each workflow's default is read or none", () => { + test("only release-please and the publish job may write; each workflow's default is read or none", () => { for (const { name, text } of workflows) expect(text, name).toMatch(/^permissions:(?: \{\}|\n {2}contents: read)$/m); - const writers = workflows.filter(({ text }) => /contents: write/.test(text)).map(({ name }) => name); + const writers = workflows.filter(({ text }) => /(?:contents|pull-requests): write/.test(text)).map((w) => w.name); expect(writers).toEqual(["release.yml"]); const release = workflows.find(({ name }) => name === "release.yml")?.text ?? ""; - expect(release.match(/contents: write/g)).toHaveLength(1); - expect(release.slice(release.indexOf("\n publish:"))).toContain("contents: write"); + const jobs = Object.fromEntries( + release.split(/\n(?= {2}[\w-]+:\n)/).map((block) => [block.match(/^ {2}([\w-]+):/)?.[1] ?? "", block] as const), + ); + const writing = (permission: string) => + Object.keys(jobs).filter((job) => jobs[job]?.includes(`${permission}: write`)); + expect(writing("contents")).toEqual(["release-please", "publish"]); + expect(writing("pull-requests")).toEqual(["release-please"]); expect(release).not.toMatch(/secrets\./); // only GITHUB_TOKEN }); });