diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e4673d58..64022bdc 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -6,60 +6,81 @@ on: - 'v*' workflow_dispatch: +permissions: + contents: write + id-token: write + +concurrency: + group: release-${{ github.ref }} + cancel-in-progress: false + jobs: - verify-mcp-package: + release: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v4 - - name: Use Node.js - uses: actions/setup-node@v4 - with: - node-version: '20.x' - registry-url: 'https://registry.npmjs.org' - cache: 'npm' + - name: Resolve release version + id: version + run: | + if [[ "${{ github.event_name }}" == "push" ]]; then + TAG="${GITHUB_REF#refs/tags/}" + else + TAG="v$(node -p "require('./package.json').version")" + fi + VERSION="${TAG#v}" + echo "tag=$TAG" >> "$GITHUB_OUTPUT" + echo "version=$VERSION" >> "$GITHUB_OUTPUT" - - name: Install dependencies - run: npm ci + - name: Use Node.js + uses: actions/setup-node@v4 + with: + node-version: '20.x' + registry-url: 'https://registry.npmjs.org' + cache: 'npm' - - name: Build package bundles - run: npm run build:packages + - name: Install dependencies + run: npm ci - - name: Smoke test package bundles - run: npm run smoke:packages + - name: Build package bundles + run: npm run build:packages - - name: Dry run publish @dotcontext/mcp - working-directory: .release/packages/mcp - run: npm publish --dry-run --access public - env: - NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + - name: Smoke test package bundles + run: npm run smoke:packages - - name: Upload @dotcontext/mcp bundle - uses: actions/upload-artifact@v4 - with: - name: dotcontext-mcp-package - path: .release/packages/mcp/ - overwrite: true + - name: Verify tag matches package.json and bundles + if: github.event_name == 'push' + run: node scripts/verify-release-version.js "${{ steps.version.outputs.tag }}" - publish-mcp-package: - if: github.event_name == 'push' - needs: verify-mcp-package - runs-on: ubuntu-latest - steps: - - name: Use Node.js - uses: actions/setup-node@v4 - with: - node-version: '20.x' - registry-url: 'https://registry.npmjs.org' + - name: Dry run publish all @dotcontext packages + run: node scripts/publish-package-bundles.js "${{ steps.version.outputs.version }}" + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + DRY_RUN: '1' + + - name: Verify npm registry authentication + if: github.event_name == 'push' + run: npm whoami + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + + - name: Publish all @dotcontext packages + if: github.event_name == 'push' + run: node scripts/publish-package-bundles.js "${{ steps.version.outputs.version }}" + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + NPM_PROVENANCE: '1' - - name: Download @dotcontext/mcp bundle - uses: actions/download-artifact@v4 - with: - name: dotcontext-mcp-package - path: .release/packages/mcp + - name: Extract changelog release notes + if: github.event_name == 'push' + run: node scripts/extract-changelog-section.js "${{ steps.version.outputs.version }}" > release-notes.md - - name: Publish @dotcontext/mcp - working-directory: .release/packages/mcp - run: npm publish --access public - env: - NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + - name: Create GitHub Release + if: github.event_name == 'push' + uses: softprops/action-gh-release@v2 + with: + tag_name: ${{ steps.version.outputs.tag }} + name: ${{ steps.version.outputs.tag }} + body_path: release-notes.md + draft: false + prerelease: false \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 628219cc..023822d0 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -92,50 +92,48 @@ The hook installer is the source of truth for supported hosts and config shapes. - Do not bump `package.json` version in feature PRs unless the change is explicitly part of release preparation. - Keep `CHANGELOG.md` aligned with the intended release line. -- For local packaging validation, use: +- Every shipped version needs a `CHANGELOG.md` section headed `## []` (for example `## [1.2.0] - YYYY-MM-DD`). The Release workflow uses that section for the GitHub Release body. + +### Preparing a release locally + +Bump the root `package.json` version, update `CHANGELOG.md`, then validate bundles: ```bash npm run release:packages:patch ``` -This prepares local release bundles under `.release/packages/` and `.release/releases/`. - -### Publishing split packages - -`release:packages:*` does not publish anything to npm. Publishing the split packages is a separate step. +This runs `build:packages`, `smoke:packages`, and copies bundles to `.release/releases/`. -1. Build and validate the package bundles: - -```bash -npm run build:packages -npm run smoke:packages -``` +### Automated release (preferred) -2. Publish from the generated bundle directory for each package you intend to release: +Pushing a tag that matches the root version (for example `v1.2.0` when `package.json` is `1.2.0`) runs [`.github/workflows/release.yml`](./.github/workflows/release.yml). The workflow: -```bash -cd .release/packages/cli -npm publish --access public +1. Builds and smoke-tests all five bundles. +2. Asserts the tag matches `package.json` and every bundle version under `.release/packages/`. +3. Publishes `@dotcontext/harness`, `@dotcontext/cli`, `@dotcontext/mcp`, `@dotcontext/integrations`, and `@dotcontext/pi` in dependency order using the `NPM_TOKEN` secret. +4. Skips any package version that is already on npm so reruns stay safe. +5. Opens a GitHub Release for the tag with notes from the matching `CHANGELOG.md` section. -cd ../harness -npm publish --access public +`workflow_dispatch` on the same workflow performs the build, smoke, and `npm publish --dry-run` checks only; it does not publish or create a GitHub Release. -cd ../mcp -npm publish --access public +Repository setup (maintainers): -cd ../integrations -npm publish --access public +- Store an npm **Automation** token with publish access to the `@dotcontext` scope in the `NPM_TOKEN` Actions secret, **or** configure [npm Trusted Publishers](https://docs.npmjs.com/trusted-publishers) for each package to trust `vinilana/dotcontext` and this workflow file. +- Prefer Trusted Publishers together with `--provenance` (the workflow enables provenance on tag pushes). If provenance must be disabled temporarily, set job env `NPM_PROVENANCE: '0'`. +- `npm publish --dry-run` does not prove registry auth; rely on the real publish step (or a manual token check) before tagging. -cd ../pi -npm publish --access public -``` +### Manual publish (fallback) -3. If npm 2FA is enabled for publishes, pass the current OTP: +If Actions cannot publish, build locally and publish from each bundle directory in order: `harness`, `cli`, `mcp`, `integrations`, `pi`. ```bash -npm publish --access public --otp= +npm run build:packages +npm run smoke:packages +node scripts/publish-package-bundles.js "$(node -p "require('./package.json').version")" ``` +For a one-off manual publish you still need a valid `NODE_AUTH_TOKEN` in the environment. If npm 2FA blocks automation tokens, use a one-time OTP on each `npm publish` as before. + Useful verification commands: ```bash @@ -151,7 +149,6 @@ Notes: - Publish from `.release/packages/`, not from the repo root. - `@dotcontext/mcp` is a separately published package. If it is missing from npm, `npx @dotcontext/mcp install` will fail with a registry `404`. - `@dotcontext/integrations` is for extension authors and host hook mappers; `@dotcontext/pi` is the Pi npm extension package. -- Run `npm publish --dry-run --access public` first if you want to inspect the tarball before the real publish. ## Pull Requests diff --git a/package.json b/package.json index 06030770..a5ce8c95 100644 --- a/package.json +++ b/package.json @@ -29,6 +29,7 @@ "build": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\" && tsc", "build:packages": "npm run build && node scripts/build-package-bundles.js", "smoke:packages": "node scripts/smoke-package-bundles.js", + "test:release-scripts": "node --test scripts/extract-changelog-section.test.js", "release:packages": "node scripts/release-packages.js", "release:packages:patch": "node scripts/release-packages.js patch", "release:packages:minor": "node scripts/release-packages.js minor", diff --git a/scripts/extract-changelog-section.js b/scripts/extract-changelog-section.js new file mode 100644 index 00000000..5ed102e2 --- /dev/null +++ b/scripts/extract-changelog-section.js @@ -0,0 +1,51 @@ +#!/usr/bin/env node + +const fs = require('fs'); +const path = require('path'); + +function extractChangelogSection(changelogContent, version) { + const headerPattern = new RegExp(`^## \\[${escapeRegExp(version)}\\]`, 'm'); + const startMatch = changelogContent.match(headerPattern); + if (!startMatch) { + throw new Error(`CHANGELOG.md is missing a section for version ${version} (expected "## [${version}]").`); + } + + const startIndex = startMatch.index; + const afterHeader = changelogContent.indexOf('\n', startIndex); + const bodyStart = afterHeader === -1 ? changelogContent.length : afterHeader + 1; + const nextSectionMatch = changelogContent.slice(bodyStart).match(/\n## \[/); + const bodyEnd = + nextSectionMatch && nextSectionMatch.index !== undefined + ? bodyStart + nextSectionMatch.index + : changelogContent.length; + + const body = changelogContent.slice(bodyStart, bodyEnd).trim(); + if (!body) { + throw new Error(`CHANGELOG.md section for version ${version} is empty.`); + } + + return body; +} + +function escapeRegExp(value) { + return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function main() { + const version = process.argv[2]; + if (!version) { + console.error('Usage: node scripts/extract-changelog-section.js '); + process.exit(1); + } + + const changelogPath = path.join(__dirname, '..', 'CHANGELOG.md'); + const content = fs.readFileSync(changelogPath, 'utf8'); + const section = extractChangelogSection(content, version); + process.stdout.write(`${section}\n`); +} + +if (require.main === module) { + main(); +} + +module.exports = { extractChangelogSection }; \ No newline at end of file diff --git a/scripts/extract-changelog-section.test.js b/scripts/extract-changelog-section.test.js new file mode 100644 index 00000000..a898823c --- /dev/null +++ b/scripts/extract-changelog-section.test.js @@ -0,0 +1,31 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { extractChangelogSection } = require('./extract-changelog-section'); + +test('extractChangelogSection returns the body for a matching version heading', () => { + const content = [ + '## [Unreleased]', + '', + '### Added', + '', + '- pending', + '', + '## [1.2.3] - 2026-01-01', + '', + '### Fixed', + '', + '- shipped fix', + '', + '## [1.2.2] - 2025-12-01', + '', + '- older', + ].join('\n'); + + const section = extractChangelogSection(content, '1.2.3'); + assert.match(section, /shipped fix/); + assert.doesNotMatch(section, /older/); +}); + +test('extractChangelogSection rejects missing versions', () => { + assert.throws(() => extractChangelogSection('## [1.0.0]\n', '2.0.0'), /missing a section/); +}); \ No newline at end of file diff --git a/scripts/publish-package-bundles.js b/scripts/publish-package-bundles.js new file mode 100644 index 00000000..644eff99 --- /dev/null +++ b/scripts/publish-package-bundles.js @@ -0,0 +1,91 @@ +#!/usr/bin/env node + +const fs = require('fs'); +const path = require('path'); +const { execFileSync } = require('child_process'); + +const bundlesRoot = path.join(__dirname, '..', '.release', 'packages'); + +/** Publish order: harness first, then packages that depend on scoped siblings last. */ +const packages = [ + { slug: 'harness', name: '@dotcontext/harness' }, + { slug: 'cli', name: '@dotcontext/cli' }, + { slug: 'mcp', name: '@dotcontext/mcp' }, + { slug: 'integrations', name: '@dotcontext/integrations' }, + { slug: 'pi', name: '@dotcontext/pi' }, +]; + +function viewPublishedVersion(packageName, version) { + try { + return execFileSync('npm', ['view', `${packageName}@${version}`, 'version'], { + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'ignore'], + }).trim(); + } catch { + return null; + } +} + +function publishBundle(packageName, slug, version) { + const bundleDir = path.join(bundlesRoot, slug); + const manifestPath = path.join(bundleDir, 'package.json'); + if (!fs.existsSync(manifestPath)) { + throw new Error(`Missing bundle for ${packageName} at ${bundleDir}.`); + } + + const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); + if (manifest.version !== version) { + throw new Error(`${packageName} bundle version is ${manifest.version}, expected ${version}.`); + } + + const published = viewPublishedVersion(packageName, version); + if (published === version) { + console.log(`skip ${packageName}@${version} (already on npm)`); + return 'skipped'; + } + + const args = ['publish', '--access', 'public']; + if (process.env.DRY_RUN === '1') { + args.push('--dry-run'); + } else if (process.env.NPM_PROVENANCE === '1') { + args.push('--provenance'); + } + + console.log(`${process.env.DRY_RUN === '1' ? 'dry-run ' : ''}publish ${packageName}@${version}`); + execFileSync('npm', args, { + cwd: bundleDir, + stdio: 'inherit', + env: process.env, + }); + return 'published'; +} + +function main() { + const version = process.argv[2]; + if (!version) { + console.error('Usage: node scripts/publish-package-bundles.js '); + process.exit(1); + } + + if (!process.env.DRY_RUN && !process.env.NODE_AUTH_TOKEN) { + console.error( + 'NODE_AUTH_TOKEN is not set. Configure the NPM_TOKEN repository secret for publish steps.' + ); + process.exit(1); + } + + const results = []; + for (const pkg of packages) { + results.push({ ...pkg, outcome: publishBundle(pkg.name, pkg.slug, version) }); + } + + const published = results.filter((entry) => entry.outcome === 'published').length; + const skipped = results.filter((entry) => entry.outcome === 'skipped').length; + console.log(`Done. published=${published} skipped=${skipped} total=${results.length}`); +} + +if (require.main === module) { + main(); +} + +module.exports = { packages, publishBundle, viewPublishedVersion }; \ No newline at end of file diff --git a/scripts/verify-release-version.js b/scripts/verify-release-version.js new file mode 100644 index 00000000..be833239 --- /dev/null +++ b/scripts/verify-release-version.js @@ -0,0 +1,67 @@ +#!/usr/bin/env node + +const fs = require('fs'); +const path = require('path'); + +const releaseSlugs = ['cli', 'harness', 'mcp', 'integrations', 'pi']; + +function parseTagVersion(tag) { + if (!tag) { + throw new Error('Missing release tag.'); + } + const normalized = tag.startsWith('refs/tags/') ? tag.slice('refs/tags/'.length) : tag; + if (!normalized.startsWith('v')) { + throw new Error(`Release tag must start with "v" (received "${normalized}").`); + } + const version = normalized.slice(1); + if (!version) { + throw new Error(`Release tag "${normalized}" does not contain a version.`); + } + return version; +} + +function readBundleVersion(slug) { + const packagePath = path.join(__dirname, '..', '.release', 'packages', slug, 'package.json'); + if (!fs.existsSync(packagePath)) { + throw new Error(`Missing bundle at ${packagePath}. Run npm run build:packages first.`); + } + return JSON.parse(fs.readFileSync(packagePath, 'utf8')).version; +} + +function main() { + const tag = process.argv[2] || process.env.GITHUB_REF_NAME; + const expectedVersion = parseTagVersion(tag); + const rootVersion = JSON.parse( + fs.readFileSync(path.join(__dirname, '..', 'package.json'), 'utf8') + ).version; + + if (rootVersion !== expectedVersion) { + console.error( + `Tag ${tag} targets version ${expectedVersion}, but package.json version is ${rootVersion}.` + ); + process.exit(1); + } + + const mismatches = []; + for (const slug of releaseSlugs) { + const bundleVersion = readBundleVersion(slug); + if (bundleVersion !== expectedVersion) { + mismatches.push(`${slug}: ${bundleVersion}`); + } + } + + if (mismatches.length > 0) { + console.error( + `Bundle versions do not match tag ${tag}:\n${mismatches.map((line) => `- ${line}`).join('\n')}` + ); + process.exit(1); + } + + console.log(`Release tag ${tag} matches package.json and all bundle versions (${expectedVersion}).`); +} + +if (require.main === module) { + main(); +} + +module.exports = { parseTagVersion }; \ No newline at end of file