| 1 | import { createHash } from 'node:crypto'; |
| 2 | import { execFileSync, spawnSync } from 'node:child_process'; |
| 3 | import { createReadStream } from 'node:fs'; |
| 4 | import { appendFile, mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises'; |
| 5 | import { tmpdir } from 'node:os'; |
| 6 | import { dirname, join, relative, resolve } from 'node:path'; |
| 7 | import { fileURLToPath, pathToFileURL } from 'node:url'; |
| 8 | import { Readable } from 'node:stream'; |
| 9 | import { compareVersions, nextVersion, parseVersion, versionFiles } from './release-version.mjs'; |
| 10 | import { prepareReleaseAssets } from './prepare-release-assets.mjs'; |
| 11 | |
| 12 | export const versionPaths = ['VERSION', 'ui/package.json', 'ui/package-lock.json', 'www/package.json', 'www/package-lock.json']; |
| 13 | const repoRoot = fileURLToPath(new URL('../', import.meta.url)); |
| 14 | const shaPattern = /^[0-9a-f]{40}$/; |
| 15 | const platforms = ['macos', 'windows', 'linux']; |
| 16 | |
| 17 | function checkContext(context) { |
| 18 | if (context.repository !== 'Lee-xeo/Claude-Cage' || !shaPattern.test(context.sourceSha) || !/^\d+$/.test(context.runId) || context.defaultBranch !== 'main') { |
| 19 | throw new Error('Invalid release repository, source commit, run ID or default branch.'); |
| 20 | } |
| 21 | } |
| 22 | const marker = context => `<!-- cage-release-run:${context.runId}; commit:${context.commitSha} -->`; |
| 23 | const message = (version, runId) => `chore(release): v${version}\n\nCage-Release-Run: ${runId}`; |
| 24 | const branch = runId => `codex/release/${runId}`; |
| 25 | const apiRoot = context => `/repos/${context.repository}`; |
| 26 | async function optional(api, path) { |
| 27 | try { return await api('GET', path); } |
| 28 | catch (error) { if (error.status === 404) return null; throw error; } |
| 29 | } |
| 30 | |
| 31 | |
| 32 | |
| 33 | async function findRelease(api, base, tag) { |
| 34 | let found = null; |
| 35 | for (let page = 1; ; page++) { |
| 36 | const releases = await api('GET', `${base}/releases?per_page=100&page=${page}`); |
| 37 | for (const release of releases) { |
| 38 | if (release.tag_name !== tag) continue; |
| 39 | if (found) throw new Error(`Multiple Releases reserve ${tag}; review them before retrying.`); |
| 40 | found = release; |
| 41 | } |
| 42 | if (releases.length < 100) return found; |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | export async function releaseNotes(root, context) { |
| 47 | if (!context.notesPath) return ''; |
| 48 | if (!/^docs\/(?:[A-Za-z0-9_.-]+\/)*[A-Za-z0-9_.-]+\.md$/.test(context.notesPath) || context.notesPath.split('/').some(part => part === '.' || part === '..')) { |
| 49 | throw new Error('Release notes must be a committed Markdown file under docs/.'); |
| 50 | } |
| 51 | if (!shaPattern.test(context.sourceSha)) throw new Error('Invalid release notes source.'); |
| 52 | const body = execFileSync('git', ['show', `${context.sourceSha}:${context.notesPath}`], { cwd: root, encoding: 'utf8', maxBuffer: 1 << 20 }).trim(); |
| 53 | if (!body || Buffer.byteLength(body) > 100000) throw new Error('Release notes must contain 1–100000 UTF-8 bytes.'); |
| 54 | return body; |
| 55 | } |
| 56 | |
| 57 | |
| 58 | |
| 59 | export async function expectedFiles(root, sourceSha, version) { |
| 60 | if (!shaPattern.test(sourceSha)) throw new Error('Invalid source commit.'); |
| 61 | const fixture = await mkdtemp(join(tmpdir(), 'cage-release-version-')); |
| 62 | try { |
| 63 | for (const path of versionPaths) { |
| 64 | const content = execFileSync('git', ['show', `${sourceSha}:${path}`], { cwd: root, maxBuffer: 20 << 20 }); |
| 65 | await mkdir(dirname(join(fixture, path)), { recursive: true }); |
| 66 | await writeFile(join(fixture, path), content); |
| 67 | } |
| 68 | return new Map([...versionFiles(fixture, version)].map(([path, text]) => [relative(fixture, path).replaceAll('\\', '/'), text])); |
| 69 | } finally { await rm(fixture, { recursive: true, force: true }); } |
| 70 | } |
| 71 | |
| 72 | export async function verifyCandidate(api, context, expected) { |
| 73 | checkContext(context); |
| 74 | parseVersion(context.version); |
| 75 | if (!shaPattern.test(context.commitSha)) throw new Error('Invalid candidate commit.'); |
| 76 | const base = apiRoot(context); |
| 77 | const commit = await api('GET', `${base}/git/commits/${context.commitSha}`); |
| 78 | if (commit.message !== message(context.version, context.runId) || commit.parents?.length !== 1 || commit.parents[0].sha !== context.sourceSha) { |
| 79 | throw new Error('Candidate does not belong to this release run and source commit.'); |
| 80 | } |
| 81 | const diff = await api('GET', `${base}/compare/${context.sourceSha}...${context.commitSha}`); |
| 82 | if (diff.status !== 'ahead' || diff.ahead_by !== 1 || diff.files?.length !== versionPaths.length || |
| 83 | diff.files.some(file => file.status !== 'modified' || !versionPaths.includes(file.filename))) { |
| 84 | throw new Error('Release candidate must change only the five application version files.'); |
| 85 | } |
| 86 | for (const [path, content] of expected) { |
| 87 | const file = await api('GET', `${base}/contents/${path}?ref=${context.commitSha}`); |
| 88 | if (file.type !== 'file' || file.encoding !== 'base64' || Buffer.from(file.content, 'base64').toString('utf8') !== content) { |
| 89 | throw new Error(`Candidate contains an unexpected change: ${path}`); |
| 90 | } |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | export async function prepareRelease({ api, root, ...context }) { |
| 95 | checkContext(context); |
| 96 | if (context.requestedVersion) parseVersion(context.requestedVersion); |
| 97 | await releaseNotes(root, context); |
| 98 | const base = apiRoot(context); |
| 99 | const main = await api('GET', `${base}/git/ref/heads/${context.defaultBranch}`); |
| 100 | const existing = await optional(api, `${base}/git/ref/heads/${branch(context.runId)}`); |
| 101 | if (existing) { |
| 102 | const commit = await api('GET', `${base}/git/commits/${existing.object.sha}`); |
| 103 | const version = /^chore\(release\): v([^\n]+)\n\nCage-Release-Run: \d+$/.exec(commit.message)?.[1]; |
| 104 | parseVersion(version); |
| 105 | if (context.requestedVersion && context.requestedVersion !== version) throw new Error('Existing candidate uses another requested version.'); |
| 106 | if (main.object.sha !== context.sourceSha && main.object.sha !== existing.object.sha) throw new Error('Main advanced; start a new explicitly requested release.'); |
| 107 | const result = { ...context, version, commitSha: existing.object.sha }; |
| 108 | await verifyCandidate(api, result, await expectedFiles(root, context.sourceSha, version)); |
| 109 | return result; |
| 110 | } |
| 111 | if (main.object.sha !== context.sourceSha) throw new Error('Main advanced after dispatch; no version was changed. Start a new release.'); |
| 112 | const current = execFileSync('git', ['show', `${context.sourceSha}:VERSION`], { cwd: root, encoding: 'utf8' }).trim(); |
| 113 | const refs = await api('GET', `${base}/git/matching-refs/tags/v`); |
| 114 | const reserved = refs.map(ref => ref.ref.replace('refs/tags/', '')); |
| 115 | for (let page = 1; ; page++) { |
| 116 | const releases = await api('GET', `${base}/releases?per_page=100&page=${page}`); |
| 117 | reserved.push(...releases.map(release => release.tag_name)); |
| 118 | if (releases.length < 100) break; |
| 119 | } |
| 120 | const version = context.requestedVersion || nextVersion(current, context.bump, reserved); |
| 121 | if (compareVersions(version, current) <= 0) throw new Error('Release version must advance.'); |
| 122 | if (context.requestedVersion) { |
| 123 | for (const tag of reserved) { |
| 124 | if (!tag.startsWith('v')) continue; |
| 125 | let previous; |
| 126 | try { previous = parseVersion(tag.slice(1)); } catch { continue; } |
| 127 | if (previous && compareVersions(version, tag.slice(1)) <= 0) throw new Error('Requested release version must exceed all reserved versions.'); |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | if (await findRelease(api, base, `v${version}`)) throw new Error(`Release v${version} is already reserved.`); |
| 132 | const files = await expectedFiles(root, context.sourceSha, version); |
| 133 | const source = await api('GET', `${base}/git/commits/${context.sourceSha}`); |
| 134 | const tree = await api('POST', `${base}/git/trees`, { |
| 135 | base_tree: source.tree.sha, |
| 136 | tree: [...files].map(([path, content]) => ({ path, mode: '100644', type: 'blob', content })), |
| 137 | }); |
| 138 | const candidate = await api('POST', `${base}/git/commits`, { |
| 139 | message: message(version, context.runId), tree: tree.sha, parents: [context.sourceSha], |
| 140 | }); |
| 141 | await api('POST', `${base}/git/refs`, { ref: `refs/heads/${branch(context.runId)}`, sha: candidate.sha }); |
| 142 | const result = { ...context, version, commitSha: candidate.sha }; |
| 143 | await verifyCandidate(api, result, files); |
| 144 | return result; |
| 145 | } |
| 146 | |
| 147 | export async function assembleRelease({ directory, output, version, commitSha, assemble = prepareReleaseAssets }) { |
| 148 | parseVersion(version); |
| 149 | if (!shaPattern.test(commitSha)) throw new Error('Invalid artifact commit.'); |
| 150 | for (const platform of platforms) { |
| 151 | const metadata = JSON.parse(await readFile(join(directory, platform, 'build-metadata.json'), 'utf8')); |
| 152 | if (metadata.schema !== 1 || metadata.platform !== platform || metadata.version !== version || metadata.commitSha !== commitSha) { |
| 153 | throw new Error(`${platform} artifact was not built from the selected version and commit.`); |
| 154 | } |
| 155 | } |
| 156 | const result = await assemble({ inputs: platforms.map(platform => join(directory, platform)), output }); |
| 157 | const required = [`Cage-${version}-macos-arm64.dmg`, `Cage-${version}-windows-amd64-setup.exe`, `Cage-${version}-linux-amd64.deb`]; |
| 158 | if (result.version !== version || required.some(name => !result.assets.includes(name))) throw new Error('All three verified platform installers are required.'); |
| 159 | return result; |
| 160 | } |
| 161 | |
| 162 | async function sha256(path) { |
| 163 | const hash = createHash('sha256'); |
| 164 | for await (const chunk of createReadStream(path)) hash.update(chunk); |
| 165 | return hash.digest('hex'); |
| 166 | } |
| 167 | export async function releaseFiles(directory) { |
| 168 | const manifest = await readFile(join(directory, 'SHA256SUMS'), 'utf8'); |
| 169 | const files = new Map(); |
| 170 | for (const line of manifest.trim().split(/\r?\n/)) { |
| 171 | const match = /^([a-f0-9]{64}) ([A-Za-z0-9][A-Za-z0-9._-]*)$/.exec(line); |
| 172 | if (!match || files.has(match[2])) throw new Error('Invalid release checksum manifest.'); |
| 173 | files.set(match[2], match[1]); |
| 174 | } |
| 175 | files.set('SHA256SUMS', await sha256(join(directory, 'SHA256SUMS'))); |
| 176 | const actual = await readdir(directory); |
| 177 | if (actual.length !== files.size || actual.some(name => !files.has(name))) throw new Error('Release output contains unlisted files.'); |
| 178 | const result = []; |
| 179 | for (const [name, digest] of files) { |
| 180 | const path = join(directory, name); |
| 181 | const info = await stat(path); |
| 182 | if (!info.isFile() || !info.size || await sha256(path) !== digest) throw new Error(`Invalid release file: ${name}`); |
| 183 | result.push({ name, path, digest: `sha256:${digest}`, size: info.size }); |
| 184 | } |
| 185 | return result; |
| 186 | } |
| 187 | |
| 188 | function assertOwned(release, context) { |
| 189 | if (!release.body?.includes(marker(context)) || release.tag_name !== `v${context.version}`) throw new Error('Existing Release belongs to another operation; refusing to change it.'); |
| 190 | } |
| 191 | function correctAsset(asset, file) { return asset?.state === 'uploaded' && asset.size === file.size && asset.digest === file.digest; } |
| 192 | function assertAssets(assets, files) { |
| 193 | if (assets.length !== files.length || files.some(file => !correctAsset(assets.find(asset => asset.name === file.name), file))) { |
| 194 | throw new Error('GitHub uploaded assets do not match the complete verified release.'); |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | export async function publishRelease({ api, upload, promote, root, files, ...context }) { |
| 199 | checkContext(context); |
| 200 | const customNotes = await releaseNotes(root, context); |
| 201 | await verifyCandidate(api, context, await expectedFiles(root, context.sourceSha, context.version)); |
| 202 | const base = apiRoot(context); |
| 203 | const main = await api('GET', `${base}/git/ref/heads/${context.defaultBranch}`); |
| 204 | if (![context.sourceSha, context.commitSha].includes(main.object.sha)) throw new Error('Main changed during the build; no Release was published.'); |
| 205 | const tag = await optional(api, `${base}/git/ref/tags/v${context.version}`); |
| 206 | if (tag && tag.object.sha !== context.commitSha) throw new Error('Version tag already points to another commit.'); |
| 207 | let release = await findRelease(api, base, `v${context.version}`); |
| 208 | if (release) { |
| 209 | assertOwned(release, context); |
| 210 | if (!release.draft) { |
| 211 | if (!tag || main.object.sha !== context.commitSha) throw new Error('Published Release has unexpected Git references.'); |
| 212 | assertAssets(await api('GET', `${base}/releases/${release.id}/assets?per_page=100`), files); |
| 213 | return release; |
| 214 | } |
| 215 | } |
| 216 | await promote(context); |
| 217 | if (!release) { |
| 218 | const notes = customNotes ? { body: customNotes } : await api('POST', `${base}/releases/generate-notes`, { tag_name: `v${context.version}`, target_commitish: context.commitSha }); |
| 219 | release = await api('POST', `${base}/releases`, { |
| 220 | tag_name: `v${context.version}`, target_commitish: context.commitSha, |
| 221 | name: `Cage ${context.version}`, draft: true, prerelease: context.version.includes('-'), |
| 222 | body: `${marker(context)}\n\n${notes.body || ''}${customNotes ? '' : `\n\nThree platform builds, package verification and automated checks completed for ${context.commitSha}. Hardware virtualization and real Claude account acceptance are separate checks; see the platform guides.`}`, |
| 223 | }); |
| 224 | } |
| 225 | const assets = await api('GET', `${base}/releases/${release.id}/assets?per_page=100`); |
| 226 | if (assets.some(asset => !files.some(file => file.name === asset.name))) throw new Error('Draft contains unexpected assets; review them before retrying.'); |
| 227 | for (const file of files) { |
| 228 | const prior = assets.find(asset => asset.name === file.name); |
| 229 | if (correctAsset(prior, file)) continue; |
| 230 | |
| 231 | const current = await api('GET', `${base}/releases/${release.id}`); |
| 232 | assertOwned(current, context); |
| 233 | if (!current.draft) throw new Error('Published assets cannot be replaced.'); |
| 234 | if (prior) await api('DELETE', `${base}/releases/assets/${prior.id}`); |
| 235 | await upload(context.repository, release.id, file); |
| 236 | } |
| 237 | assertAssets(await api('GET', `${base}/releases/${release.id}/assets?per_page=100`), files); |
| 238 | return api('PATCH', `${base}/releases/${release.id}`, { draft: false, make_latest: context.version.includes('-') ? 'false' : 'true' }); |
| 239 | } |
| 240 | |
| 241 | export function workflowContext(env, event) { |
| 242 | const context = { |
| 243 | repository: env.GITHUB_REPOSITORY, sourceSha: env.RELEASE_SOURCE_SHA || env.GITHUB_SHA, |
| 244 | runId: env.GITHUB_RUN_ID, defaultBranch: event.repository?.default_branch, bump: event.inputs?.bump, |
| 245 | version: env.RELEASE_VERSION, commitSha: env.RELEASE_COMMIT_SHA, |
| 246 | requestedVersion: event.inputs?.version?.replace(/^v/, '') || undefined, notesPath: event.inputs?.notes_path || undefined, |
| 247 | }; |
| 248 | checkContext(context); |
| 249 | if (env.GITHUB_ACTIONS !== 'true' || env.GITHUB_EVENT_NAME !== 'workflow_dispatch' || env.GITHUB_REF !== 'refs/heads/main') { |
| 250 | throw new Error('Release mutations require an explicit workflow dispatch on main.'); |
| 251 | } |
| 252 | return context; |
| 253 | } |
| 254 | |
| 255 | async function main() { |
| 256 | const context = workflowContext(process.env, JSON.parse(await readFile(process.env.GITHUB_EVENT_PATH, 'utf8'))); |
| 257 | const token = process.env.GH_TOKEN || process.env.GITHUB_TOKEN; |
| 258 | if (!token) throw new Error('Missing release token.'); |
| 259 | const headers = { authorization: `Bearer ${token}`, accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' }; |
| 260 | const api = async (method, path, body) => { |
| 261 | const response = await fetch(`https://api.github.com${path}`, { |
| 262 | method, headers: { ...headers, 'content-type': 'application/json' }, redirect: 'error', |
| 263 | body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(60000), |
| 264 | }); |
| 265 | if (!response.ok) { |
| 266 | const error = new Error(`GitHub ${method} ${path.split('?')[0]} failed (${response.status}).`); |
| 267 | error.status = response.status; throw error; |
| 268 | } |
| 269 | return response.status === 204 ? null : response.json(); |
| 270 | }; |
| 271 | const output = async values => { |
| 272 | if (!process.env.GITHUB_OUTPUT) throw new Error('Missing workflow output file.'); |
| 273 | await appendFile(process.env.GITHUB_OUTPUT, Object.entries(values).map(([key, value]) => `${key}=${value}\n`).join('')); |
| 274 | }; |
| 275 | if (process.argv[2] === 'prepare') { |
| 276 | const prepared = await prepareRelease({ api, root: repoRoot, ...context }); |
| 277 | await output({ version: prepared.version, commit_sha: prepared.commitSha, source_sha: prepared.sourceSha }); |
| 278 | console.log(`Prepared v${prepared.version} from ${prepared.sourceSha}; candidate ${prepared.commitSha}.`); |
| 279 | } else if (process.argv[2] === 'publish') { |
| 280 | const directory = resolve('_output/release-artifacts'); |
| 281 | const destination = resolve('_output/publish'); |
| 282 | await assembleRelease({ directory, output: destination, version: context.version, commitSha: context.commitSha }); |
| 283 | const files = await releaseFiles(destination); |
| 284 | const release = await publishRelease({ api, root: repoRoot, files, ...context, |
| 285 | promote: async candidate => { |
| 286 | const result = spawnSync('git', ['-c', 'credential.helper=!gh auth git-credential', 'push', '--atomic', |
| 287 | `https://github.com/${candidate.repository}.git`, `${candidate.commitSha}:refs/heads/main`, `${candidate.commitSha}:refs/tags/v${candidate.version}`], |
| 288 | { cwd: repoRoot, env: { ...process.env, GH_TOKEN: token }, encoding: 'utf8' }); |
| 289 | if (result.status !== 0) throw new Error('Atomic main/tag promotion failed; no public Release was created. Check branch rules and newer commits.'); |
| 290 | }, |
| 291 | upload: async (repository, id, file) => { |
| 292 | const response = await fetch(`https://uploads.github.com/repos/${repository}/releases/${id}/assets?name=${encodeURIComponent(file.name)}`, { |
| 293 | method: 'POST', headers: { ...headers, 'content-type': 'application/octet-stream', 'content-length': String(file.size) }, |
| 294 | redirect: 'error', body: Readable.toWeb(createReadStream(file.path)), duplex: 'half', signal: AbortSignal.timeout(20 * 60 * 1000), |
| 295 | }); |
| 296 | if (!response.ok) throw new Error(`Uploading ${file.name} failed (${response.status}); the draft remains private.`); |
| 297 | if (!correctAsset(await response.json(), file)) throw new Error(`GitHub did not confirm the checksum of ${file.name}; the draft remains private.`); |
| 298 | }, |
| 299 | }); |
| 300 | await output({ tag: `v${context.version}`, url: release.html_url }); |
| 301 | console.log(`Published ${release.html_url}`); |
| 302 | } else throw new Error('Usage: release-control.mjs prepare|publish (explicit release workflow only).'); |
| 303 | } |
| 304 | |
| 305 | if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) { |
| 306 | main().catch(error => { console.error(error.message); process.exitCode = 1; }); |
| 307 | } |