Use Claude Code, Codex, VSCode, Pi, and OpenCode (and 6 other harnesses) for free (1.3B+ free tokens) from your terminal, app, IDE, or phone, and now from the browser with native browser sessions (multi-harness + multi-model) like OpenClaw (voice supported + ToS friendly)
Python
patch: Automate release versions and GitHub Releases (#1903)
Ali Khokhar9c4d81a3f02c
diff --git a/.github/ISSUE_TEMPLATE/bug-report.yml b/.github/ISSUE_TEMPLATE/bug-report.ymlindex 5c891556..6b4d9656 100644--- a/.github/ISSUE_TEMPLATE/bug-report.yml+++ b/.github/ISSUE_TEMPLATE/bug-report.yml@@ -7,7 +7,7 @@ body:id: fcc-versionattributes:label: FCC version- description: Run `fcc-server --version` and include one version in `number.number.number` format. If FCC did not install, enter `None`.+ description: Run `fcc-server --version` and include one version exactly as printed, including any development suffix. If FCC did not install, enter `None`.placeholder: "The version is 1.22.333, or None"validations:required: truediff --git a/.github/actions/ci-environment/action.yml b/.github/actions/ci-environment/action.ymlindex b8a330c8..438865dd 100644--- a/.github/actions/ci-environment/action.yml+++ b/.github/actions/ci-environment/action.yml@@ -44,6 +44,13 @@ outputs:runs:using: compositesteps:+ - name: Fetch canonical release tags+ shell: bash+ env:+ CI_SERVER: ${{ github.server_url }}+ CI_REPOSITORY: ${{ github.repository }}+ run: git fetch --prune --no-tags "$CI_SERVER/$CI_REPOSITORY.git" '+refs/tags/*:refs/tags/*'+- name: Prepare cache identityid: identityshell: bashdiff --git a/.github/workflows/post-merge.yml b/.github/workflows/post-merge.ymlindex 55ea4343..3d99fe81 100644--- a/.github/workflows/post-merge.yml+++ b/.github/workflows/post-merge.yml@@ -7,6 +7,11 @@ env:on:workflow_dispatch:+ inputs:+ release_commit:+ description: Full main commit SHA to retry (defaults to this workflow commit)+ required: false+ type: stringpush:branches: [main]@@ -37,7 +42,7 @@ jobs:- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1with:ref: ${{ github.sha }}- fetch-depth: 1+ fetch-depth: 0- name: Set up CI environmentid: environment@@ -81,21 +86,13 @@ jobs:timeout-minutes: 15environment: pypipermissions:- contents: read+ contents: writeid-token: writesteps:- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1with:ref: ${{ github.sha }}- fetch-depth: 2-- - name: Fetch previous revision- env:- BEFORE_SHA: ${{ github.event.before }}- run: |- if [ -n "$BEFORE_SHA" ]; then- git fetch --no-tags --depth=1 origin "$BEFORE_SHA"- fi+ fetch-depth: 0- name: Set up CI environmentuses: ./.github/actions/ci-environment@@ -105,38 +102,11 @@ jobs:lookup-only: "true"sync-dependencies: "false"- - name: Detect release- id: release+ - name: Publish releaseenv:- BEFORE_SHA: ${{ github.event.before }}- HEAD_SHA: ${{ github.sha }}+ GH_TOKEN: ${{ github.token }}+ RELEASE_REPOSITORY: ${{ github.repository }}+ RELEASE_COMMIT: ${{ inputs.release_commit || github.sha }}run: |- uv run --no-project --python "$(cat .python-version)" python - <<'PY'- import os- import subprocess- import tomllib- from pathlib import Path-- head = os.environ["HEAD_SHA"]- before = os.environ.get("BEFORE_SHA") or f"{head}^"- def version(revision):- result = subprocess.run(- ["git", "show", f"{revision}:pyproject.toml"],- check=True, capture_output=True, text=True,- )- return tomllib.loads(result.stdout)["project"]["version"]- current, previous = version(head), version(before)- with Path(os.environ["GITHUB_OUTPUT"]).open("a", encoding="utf-8") as output:- output.write(f"changed={str(current != previous).lower()}\n")- print(f"Release version: {previous} -> {current}")- PY-- - name: Build and validate release- if: steps.release.outputs.changed == 'true'- run: |- uv build --no-sources --out-dir "$RUNNER_TEMP/fcc-release"- uv run --no-project --python "$(cat .python-version)" python scripts/validate_release.py "$RUNNER_TEMP/fcc-release"-- - name: Publish release- if: steps.release.outputs.changed == 'true'- run: uv publish --trusted-publishing always "$RUNNER_TEMP/fcc-release/"*+ uv run --no-project --python "$(cat .python-version)" python -m scripts.publish_release \+ --repository "$RELEASE_REPOSITORY" --commit "$RELEASE_COMMIT"diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.ymlindex 8ef74adc..85ec74c7 100644--- a/.github/workflows/tests.yml+++ b/.github/workflows/tests.yml@@ -21,37 +21,6 @@ concurrency:cancel-in-progress: truejobs:- version-policy:- name: Version policy- runs-on: ubuntu-latest- timeout-minutes: 15- permissions:- contents: read- steps:- - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1- with:- ref: ${{ github.event.pull_request.head.sha }}- repository: ${{ github.event.pull_request.head.repo.full_name }}- fetch-depth: 0-- - name: Fetch target revision- env:- BASE_SHA: ${{ github.event.pull_request.base.sha }}- BASE_REPOSITORY: ${{ github.event.pull_request.base.repo.full_name }}- run: git fetch --no-tags "https://github.com/$BASE_REPOSITORY.git" "$BASE_SHA"-- - name: Set up CI environment- uses: ./.github/actions/ci-environment- with:- uv-version: ${{ env.CI_UV_VERSION }}- runner-label: ubuntu-latest-- - name: Check version policy- env:- BASE_SHA: ${{ github.event.pull_request.base.sha }}- HEAD_SHA: ${{ github.event.pull_request.head.sha }}- run: uv run --locked --group dev python scripts/check_version_policy.py --base "$BASE_SHA" --head "$HEAD_SHA"-no-suppressions-or-legacy-annotations:name: Ban suppressions and legacy annotationsruns-on: ubuntu-latest@@ -63,7 +32,7 @@ jobs:with:ref: ${{ github.event.pull_request.head.sha || github.ref }}repository: ${{ github.event.pull_request.head.repo.full_name || github.repository }}- fetch-depth: 1+ fetch-depth: 0- name: "Fail on type ignores and legacy future annotations"run: |@@ -94,7 +63,7 @@ jobs:with:ref: ${{ github.event.pull_request.head.sha || github.ref }}repository: ${{ github.event.pull_request.head.repo.full_name || github.repository }}- fetch-depth: 1+ fetch-depth: 0- name: Set up CI environmentuses: ./.github/actions/ci-environment@@ -126,7 +95,7 @@ jobs:with:ref: ${{ github.event.pull_request.head.sha || github.ref }}repository: ${{ github.event.pull_request.head.repo.full_name || github.repository }}- fetch-depth: 1+ fetch-depth: 0- name: Set up CI environmentuses: ./.github/actions/ci-environment@@ -159,7 +128,7 @@ jobs:with:ref: ${{ github.event.pull_request.head.sha || github.ref }}repository: ${{ github.event.pull_request.head.repo.full_name || github.repository }}- fetch-depth: 1+ fetch-depth: 0- name: Set up CI environmentuses: ./.github/actions/ci-environmentdiff --git a/.github/workflows/validate-bug-report-version.yml b/.github/workflows/validate-bug-report-version.ymlindex e1db5412..27d180d9 100644--- a/.github/workflows/validate-bug-report-version.yml+++ b/.github/workflows/validate-bug-report-version.yml@@ -29,8 +29,8 @@ jobs:issue_number,});const fieldPattern = "^### FCC version\\r?\\n+\\s*([^\\r\\n]+)";- const versionPattern = "(?:^|[^0-9A-Za-z_.])v?([0-9]+\\.[0-9]+\\.[0-9]+)(?![0-9A-Za-z_+-]|\\.[0-9A-Za-z_])";- const projectVersionPattern = "^\\s*version\\s*=\\s*([\"'])([0-9]+\\.[0-9]+\\.[0-9]+)\\1\\s*(?:#.*)?$";+ const releaseVersionPattern = "^v((?:0|[1-9][0-9]*)\\.(?:0|[1-9][0-9]*)\\.(?:0|[1-9][0-9]*))$";+ const versionPattern = "(?:^|[^0-9A-Za-z_.])v?([0-9]+\\.[0-9]+\\.[0-9]+(?:\\.dev[0-9]+(?:\\+g[0-9a-f]+(?:\\.d[0-9]{8})?)?|\\+d[0-9]{8})?)(?![0-9A-Za-z_+-]|\\.[0-9A-Za-z_])";const match = (issue.body || "").match(new RegExp(fieldPattern, "m"));const fieldValue = match?.[1]?.trim() || "";const versionMatches = [...fieldValue.matchAll(new RegExp(versionPattern, "g"))];@@ -70,22 +70,6 @@ jobs:return false;};- const projectVersionFromToml = (pyproject) => {- let inProjectSection = false;- for (const line of pyproject.split(/\r?\n/)) {- const stripped = line.trim();- if (stripped === "[project]") {- inProjectSection = true;- continue;- }- if (inProjectSection && stripped.startsWith("[")) return undefined;- if (!inProjectSection) continue;- const projectVersion = line.match(new RegExp(projectVersionPattern));- if (projectVersion !== null) return projectVersion[2];- }- return undefined;- };-if (!valid) {await deleteManagedComment(outdatedComment);if (!labels.has(labelName)) {@@ -98,7 +82,7 @@ jobs:...repo,name: labelName,color: "d4c5f9",- description: "FCC version must contain number.number.number or be None",+ description: "FCC version must contain one installed version or be None",});} catch (createError) {if (createError.status !== 422) throw createError;@@ -114,7 +98,7 @@ jobs:await github.rest.issues.createComment({...repo,issue_number,- body: `${invalidMarker}\nPlease edit **FCC version** so it contains one \`number.number.number\` value, such as \`1.22.333\`, or is exactly \`None\`. Run \`fcc-server --version\` to find the installed version.`,+ body: `${invalidMarker}\nPlease edit **FCC version** so it contains one version copied from \`fcc-server --version\`, including any development suffix, or is exactly \`None\`.`,});}return;@@ -129,29 +113,23 @@ jobs:}await deleteManagedComment(invalidComment);- if (reportedVersion === undefined) {+ // Checkout versions identify development source, not published releases.+ if (reportedVersion === undefined || reportedVersion.includes(".dev") || reportedVersion.includes("+")) {await deleteManagedComment(outdatedComment);return;}- const defaultBranch = context.payload.repository.default_branch;- const { data: versionFile } = await github.rest.repos.getContent({- ...repo,- path: "pyproject.toml",- ref: defaultBranch,- });- if (- Array.isArray(versionFile)- || versionFile.type !== "file"- || versionFile.encoding !== "base64"- || !versionFile.content- ) {- throw new Error(`Could not read pyproject.toml from ${defaultBranch}`);+ let release;+ try {+ ({ data: release } = await github.rest.repos.getLatestRelease(repo));+ } catch (error) {+ if (error.status !== 404) throw error;+ await deleteManagedComment(outdatedComment);+ return;}- const pyproject = Buffer.from(versionFile.content, "base64").toString("utf8");- const latestVersion = projectVersionFromToml(pyproject);- if (latestVersion === undefined) {- throw new Error(`Could not read the project version from ${defaultBranch}`);+ const latestVersion = release.tag_name.match(new RegExp(releaseVersionPattern))?.[1];+ if (!latestVersion || release.draft || release.prerelease) {+ throw new Error("Latest release must have a stable vMAJOR.MINOR.PATCH tag");}if (!isOlderVersion(reportedVersion, latestVersion)) {@@ -159,7 +137,7 @@ jobs:return;}- const body = `${outdatedMarker}\nThis report uses FCC \`${reportedVersion}\`, while the current version on \`${defaultBranch}\` is \`${latestVersion}\`. Please [update FCC](${context.payload.repository.html_url}#install), restart FCC, and check whether the issue still occurs. The update may already contain the fix.`;+ const body = `${outdatedMarker}\nThis report uses FCC \`${reportedVersion}\`, while the latest published version is \`${latestVersion}\`. Please [update FCC](${context.payload.repository.html_url}#update), restart FCC, and check whether the issue still occurs. The update may already contain the fix.`;if (outdatedComment === undefined) {await github.rest.issues.createComment({...repo,diff --git a/.github/workflows/version-policy.yml b/.github/workflows/version-policy.ymlnew file mode 100644index 00000000..483fc2f5--- /dev/null+++ b/.github/workflows/version-policy.yml@@ -0,0 +1,51 @@+name: Release intent++env:+ CI_UV_VERSION: "0.12.13"+ UV_MALWARE_CHECK: "1"+ UV_PREVIEW_FEATURES: "malware-check"++on:+ pull_request:+ types: [opened, synchronize, reopened, edited, ready_for_review]++concurrency:+ group: release-intent-${{ github.event.pull_request.number }}+ cancel-in-progress: true++jobs:+ version-policy:+ name: Version policy+ runs-on: ubuntu-latest+ timeout-minutes: 15+ permissions:+ contents: read+ pull-requests: read+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1+ with:+ ref: ${{ github.event.pull_request.head.sha }}+ repository: ${{ github.event.pull_request.head.repo.full_name }}+ fetch-depth: 0++ - name: Read current pull request+ env:+ GH_TOKEN: ${{ github.token }}+ PR_REPOSITORY: ${{ github.repository }}+ PR_NUMBER: ${{ github.event.pull_request.number }}+ BASE_REPOSITORY_URL: ${{ github.server_url }}/${{ github.repository }}.git+ run: |+ gh api "repos/$PR_REPOSITORY/pulls/$PR_NUMBER" > "$RUNNER_TEMP/release-pr.json"+ base=$(jq -r .base.sha "$RUNNER_TEMP/release-pr.json")+ git fetch --no-tags "$BASE_REPOSITORY_URL" "$base"++ - name: Set up CI environment+ uses: ./.github/actions/ci-environment+ with:+ uv-version: ${{ env.CI_UV_VERSION }}+ runner-label: ubuntu-latest++ - name: Check version policy+ env:+ HEAD_SHA: ${{ github.event.pull_request.head.sha }}+ run: uv run --locked python scripts/check_version_policy.py --head "$HEAD_SHA" --pr-json "$RUNNER_TEMP/release-pr.json"diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 1037a71c..3a3c7741 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -9,6 +9,12 @@ Thanks for helping improve Free Claude Code. Keep changes focused, test the beha- For bugs, include every model mapping, the active model when the failure occurred, the complete error, and reproducible steps.- Add focused tests for behavior changes and relevant edge cases.+## Pull Request Titles++Changes to `assets/`, `scripts/`, `src/`, `.python-version`, `pyproject.toml`, or `uv.lock` require a title starting with `patch: `, `minor: `, or `major: ` followed by a description. Use exactly one space after the colon.++PRs without changes to those paths must not use a release prefix. Do not edit version numbers. Publishing calculates the version after merge, creates its Git tag, and publishes to PyPI and GitHub Releases.+## Development SetupInstall [uv](https://docs.astral.sh/uv/) and Python 3.14, then run directly from the checkout:@@ -54,7 +60,3 @@ GitHub CI runs Ruff in check-only mode and also bans `# type: ignore`, `# ty: ig- Keep shared Anthropic protocol behavior under `src/free_claude_code/core/anthropic/` rather than importing utilities from another provider.- Keep provider-specific configuration in the provider that owns it.- Remove dead compatibility code when completing migrations unless preserving a published interface is explicitly required.--## Versioning--Changes to runtime code, packaging, dependencies, or install/CI scripts require a semantic version bump in `pyproject.toml` and a matching `uv lock` update in the same commit. Documentation, tests, smoke coverage, and repository configuration do not require a version bump by themselves.diff --git a/pyproject.toml b/pyproject.tomlindex 4e62a6cd..ee74e01d 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -1,10 +1,10 @@[build-system]-requires = ["hatchling"]+requires = ["hatchling", "hatch-vcs>=0.5.0"]build-backend = "hatchling.build"[project]name = "free-claude-code"-version = "6.2.66"+dynamic = ["version"]description = "Local proxy connecting coding agents to OpenAI-compatible AI providers"readme = "README.md"license = "AGPL-3.0-only"@@ -63,6 +63,9 @@ voice_local = ["librosa>=1.0.0",]+[tool.hatch.version]+source = "vcs"+[tool.hatch.build.targets.wheel]packages = ["src/free_claude_code"]@@ -72,6 +75,7 @@ packages = ["src/free_claude_code"][tool.uv]required-version = ">=0.12.13"+cache-keys = [{ file = "pyproject.toml" }, { git = { commit = true, tags = true } }][tool.uv.sources]torch = { index = "pytorch-cu130" }diff --git a/scripts/check_version_policy.py b/scripts/check_version_policy.pyindex 6514ea87..84de950c 100644--- a/scripts/check_version_policy.py+++ b/scripts/check_version_policy.py@@ -1,122 +1,125 @@-"""Require one version increment exactly when a PR changes release inputs."""+"""Validate release intent against changed files and calculate one version bump."""import argparse+import json+import reimport subprocessimport tomllib--import tomlkit-from packaging.version import Version+from pathlib import PathRELEASE_FILES = {".python-version", "pyproject.toml", "uv.lock"}RELEASE_DIRS = ("assets/", "scripts/", "src/")+VERSION = re.compile(r"(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)")+PREFIX = re.compile(r"(patch|minor|major): \S[^\r\n]*")+RESERVED = re.compile(r"\s*(patch|minor|major)\s*[:\uff1a]", re.IGNORECASE)def git(*args: str) -> str:return subprocess.run(["git", *args], check=True, capture_output=True, text=True, encoding="utf-8"- ).stdout.strip()+ ).stdout.rstrip("\r\n")-def blob(revision: str, path: str) -> str | None:- result = subprocess.run(- ["git", "show", f"{revision}:{path}"],- check=False,- capture_output=True,- text=True,- encoding="utf-8",+def changed_paths(base: str, head: str) -> list[str]:+ return list(+ filter(+ None,+ git("diff", "--no-renames", "--name-only", "-z", base, head).split("\0"),+ ))- return result.stdout if result.returncode == 0 else None-def root_package(document: dict) -> dict:- entries = [- entry- for entry in document.get("package", [])- if entry.get("name") == "free-claude-code"- and entry.get("source") == {"editable": "."}+def release_paths(paths: list[str]) -> list[str]:+ return [+ path for path in paths if path in RELEASE_FILES or path.startswith(RELEASE_DIRS)]- if len(entries) != 1:- raise ValueError("uv.lock must contain exactly one editable FCC package")- return entries[0]---def version_at(revision: str) -> str:- project = tomllib.loads(blob(revision, "pyproject.toml") or "")["project"]- if project["name"] != "free-claude-code":- raise ValueError("Project name must be free-claude-code")- value = project["version"]- if not isinstance(value, str):- raise ValueError("Project version must be a string")- parsed = Version(value)- if value != f"{parsed.major}.{parsed.minor}.{parsed.micro}":- raise ValueError("Project version must use the format MAJOR.MINOR.PATCH")- lock = root_package(tomllib.loads(blob(revision, "uv.lock") or ""))- if lock["version"] != value:- raise ValueError("pyproject.toml and uv.lock versions must agree")- return value---def without_release_version(text: str | None, path: str) -> str | None:- if text is None:- return None- document = tomlkit.parse(text)- if path == "pyproject.toml":- document["project"]["version"] = "FCC_VERSION"- else:- for package in document["package"]:- if package["name"] == "free-claude-code" and package.get("source") == {- "editable": "."- }:- package["version"] = "FCC_VERSION"- return tomlkit.dumps(document)---def check(base: str, head: str) -> None:- base = git("rev-parse", "--verify", "--end-of-options", f"{base}^{{commit}}")- head = git("rev-parse", "--verify", "--end-of-options", f"{head}^{{commit}}")- ancestor = git("merge-base", base, head)- old, new = version_at(base), version_at(head)- changed = git("diff", "--no-renames", "--name-only", "-z", ancestor, head).split(- "\0"- )- release_paths = []- for path in changed:- if path not in RELEASE_FILES and not path.startswith(RELEASE_DIRS):- continue- if path in {"pyproject.toml", "uv.lock"} and without_release_version(- blob(ancestor, path), path- ) == without_release_version(blob(head, path), path):- continue- release_paths.append(path)- print(f"FCC version: {old} -> {new}")- print("Release changes: " + (", ".join(release_paths) or "none"))- previous = Version(old)- allowed = {- f"{previous.major}.{previous.minor}.{previous.micro + 1}",- f"{previous.major}.{previous.minor + 1}.0",- f"{previous.major + 1}.0.0",- }- if release_paths and new not in allowed:+++def release_kind(title: str, paths: list[str]) -> str | None:+ match = PREFIX.fullmatch(title)+ released = release_paths(paths)+ if not match and RESERVED.match(title):raise ValueError(- "Version must increase by exactly one patch, minor, or major increment "- "from the target branch, resetting lower components to zero. "- f"Allowed versions: {', '.join(sorted(allowed))}"+ "Use exactly patch: , minor: , or major: followed by a description")- if not release_paths and new != old:- raise ValueError("Version must stay unchanged without release changes")+ if released and not match:+ raise ValueError("Release changes require a patch: , minor: , or major: title")+ if not released and match:+ raise ValueError("A non-release PR must not use a release prefix")+ return match[1] if match else None+++def next_version(previous: str, kind: str) -> str:+ match = VERSION.fullmatch(previous)+ if not match:+ raise ValueError(f"Invalid release version: {previous}")+ major, minor, patch = map(int, match.groups())+ if kind == "major":+ return f"{major + 1}.0.0"+ if kind == "minor":+ return f"{major}.{minor + 1}.0"+ if kind == "patch":+ return f"{major}.{minor}.{patch + 1}"+ raise ValueError(f"Invalid release kind: {kind}")+++def check_packaging(head: str) -> None:+ project = tomllib.loads(git("show", f"{head}:pyproject.toml"))["project"]+ if (+ project["name"] != "free-claude-code"+ or "version" in project+ or "version" not in project.get("dynamic", [])+ ):+ raise ValueError("FCC must declare a dynamic version without project.version")+ lock = tomllib.loads(git("show", f"{head}:uv.lock"))+ roots = [+ p+ for p in lock["package"]+ if p["name"] == "free-claude-code" and p.get("source") == {"editable": "."}+ ]+ if len(roots) != 1 or "version" in roots[0]:+ raise ValueError("uv.lock must have one editable FCC package without a version")+++def check(base: str, head: str, title: str) -> None:+ base = git("rev-parse", "--verify", "--end-of-options", f"{base}^{{commit}}")+ head = git("rev-parse", "--verify", "--end-of-options", f"{head}^{{commit}}")+ paths = changed_paths(git("merge-base", base, head), head)+ print("Release changes: " + (", ".join(release_paths(paths)) or "none"))+ kind = release_kind(title, paths)+ check_packaging(head)+ print(f"Version policy passed: {kind or 'no release'}")def main() -> int:parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--base", required=True)+ parser.add_argument("--base")parser.add_argument("--head", required=True)+ parser.add_argument("--title")+ parser.add_argument("--pr-json", type=Path)args = parser.parse_args()try:- check(args.base, args.head)- except (ValueError, KeyError, TypeError, subprocess.CalledProcessError) as error:+ if args.pr_json:+ pr = json.loads(args.pr_json.read_text(encoding="utf-8"))+ if pr["head"]["sha"] != git(+ "rev-parse", "--verify", "--end-of-options", f"{args.head}^{{commit}}"+ ):+ raise ValueError("PR head changed; use the current policy run")+ base, title = pr["base"]["sha"], pr["title"]+ else:+ base, title = args.base, args.title+ if not base or title is None:+ raise ValueError("Provide --pr-json or both --base and --title")+ check(base, args.head, title)+ except (+ ValueError,+ KeyError,+ TypeError,+ OSError,+ subprocess.CalledProcessError,+ ) as error:print(f"Version policy failed: {error}")return 1- print("Version policy passed")return 0diff --git a/scripts/publish_release.py b/scripts/publish_release.pynew file mode 100644index 00000000..e8d56179--- /dev/null+++ b/scripts/publish_release.py@@ -0,0 +1,207 @@+"""Publish one main commit, resuming its tag and staged distribution files."""++import argparse+import hashlib+import json+import re+import subprocess+import sys+import tempfile+from pathlib import Path++from .check_version_policy import (+ VERSION,+ changed_paths,+ git,+ next_version,+ release_kind,+ release_paths,+)+++def command(args: list[str], *, cwd: Path | None = None) -> str:+ return subprocess.run(+ args, cwd=cwd, check=True, capture_output=True, text=True, encoding="utf-8"+ ).stdout+++def distribution_names(version: str) -> tuple[str, str]:+ stem = f"free_claude_code-{version}"+ return f"{stem}-py3-none-any.whl", f"{stem}.tar.gz"+++class Publisher:+ def __init__(self, repository: str) -> None:+ if not re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repository):+ raise ValueError("Expected owner/repository")+ self.repository = repository+ self.validator = Path(__file__).with_name("validate_release.py").resolve()++ def gh(self, *args: str) -> str:+ return command(["gh", "release", *args, "--repo", self.repository])++ def releases(self) -> dict:+ pages = json.loads(+ command(+ [+ "gh",+ "api",+ "--paginate",+ "--slurp",+ f"repos/{self.repository}/releases?per_page=100",+ ]+ )+ )+ return {release["tag_name"]: release for page in pages for release in page}++ def publish(self, target: str) -> None:+ if not re.fullmatch(r"[0-9a-f]{40}", target):+ raise ValueError("Release target must be a full commit SHA")+ command(["git", "fetch", "--tags", "origin", "main"])+ history = git("rev-list", "--first-parent", "origin/main").splitlines()+ if target not in history:+ raise ValueError("Release target is not on main's first-parent history")+ title = git("show", "-s", "--format=%s", target)+ kind = release_kind(title, changed_paths(f"{target}^", target))+ if kind is None:+ print(f"No release for {target}")+ return++ tags = {}+ # Peeled annotated-tag entries follow their unpeeled entries.+ for line in git("show-ref", "--tags", "--dereference").splitlines():+ sha, ref = line.split()+ name = ref.removeprefix("refs/tags/").removesuffix("^{}")+ if name.startswith("v") and VERSION.fullmatch(name[1:]):+ tags[name] = sha+ previous = None+ for sha in history[history.index(target) + 1 :]:+ names = [name for name, commit in tags.items() if commit == sha]+ if names:+ if len(names) != 1:+ raise ValueError(f"Ambiguous release tags at {sha}")+ previous = names[0]+ break+ if release_paths(changed_paths(f"{sha}^", sha)):+ raise ValueError(+ f"Earlier release {sha} is unfinished; retry its post-merge run"+ )+ if previous is None:+ raise ValueError("No baseline release tag found")+ releases = self.releases()+ predecessor = releases.get(previous)+ if not predecessor or predecessor["draft"] or predecessor["prerelease"]:+ raise ValueError(+ f"Earlier release {previous} is unfinished; retry its post-merge run"+ )+ version = next_version(previous[1:], kind)+ tag = f"v{version}"+ if any(sha == target and name != tag for name, sha in tags.items()):+ raise ValueError("Target already has another version")+ if tag in tags and tags[tag] != target:+ raise ValueError(f"Tag {tag} belongs to a different commit")+ release = releases.get(tag)+ if release and tag not in tags:+ raise ValueError(f"Release {tag} has no matching remote tag")+ if release and release["prerelease"]:+ raise ValueError(f"Release {tag} unexpectedly is a prerelease")+ if release and not release["draft"]:+ print(f"{tag} already published")+ return+ if tag not in tags:+ command(["git", "tag", tag, target])+ command(["git", "push", "origin", f"refs/tags/{tag}"])+ if release is None:+ self.gh(+ "create",+ tag,+ "--draft",+ "--verify-tag",+ "--title",+ tag,+ "--generate-notes",+ "--notes-start-tag",+ previous,+ )+ print(f"Publishing {tag} from {target}")+ with tempfile.TemporaryDirectory(prefix="fcc-release-") as temporary:+ root = Path(temporary).resolve()+ source, dist = root / "source", root / "dist"+ dist.mkdir()+ command(["git", "worktree", "add", "--detach", str(source), target])+ try:+ if command(["git", "status", "--porcelain"], cwd=source).strip():+ raise ValueError("Release source must be clean")+ self.stage(tag, version, source, dist)+ command(+ [+ "uv",+ "publish",+ "--trusted-publishing",+ "always",+ *(str(dist / name) for name in distribution_names(version)),+ ]+ )+ self.gh("edit", tag, "--draft=false", "--latest", "--verify-tag")+ finally:+ if not source.is_relative_to(root):+ raise ValueError("Release worktree escaped its temporary directory")+ command(["git", "worktree", "remove", "--force", str(source)])++ def validate(self, source: Path, dist: Path, version: str) -> None:+ command(+ [sys.executable, str(self.validator), str(dist), "--version", version],+ cwd=source,+ )++ def stage(self, tag: str, version: str, source: Path, dist: Path) -> None:+ names = set(distribution_names(version))+ assets = self.releases()[tag]["assets"]+ if any(asset["name"] not in names for asset in assets):+ raise ValueError(f"Unexpected assets on {tag}")+ complete = (+ {asset["name"] for asset in assets} == names+ and len(assets) == 2+ and all(asset["state"] == "uploaded" for asset in assets)+ )+ if complete:+ self.gh("download", tag, "--dir", str(dist))+ else:+ # Publication never begins until both uploaded assets are verified.+ for asset in assets:+ self.gh("delete-asset", tag, asset["name"], "--yes")+ command(["uv", "build", "--no-sources", "--out-dir", str(dist)], cwd=source)+ self.validate(source, dist, version)+ self.gh("upload", tag, *(str(dist / name) for name in sorted(names)))+ assets = self.releases()[tag]["assets"]+ if {asset["name"] for asset in assets} != names or len(assets) != 2:+ raise ValueError(f"Incomplete staged distributions for {tag}")+ for asset in assets:+ data = (dist / asset["name"]).read_bytes()+ digest = "sha256:" + hashlib.sha256(data).hexdigest()+ if (+ asset["state"] != "uploaded"+ or asset["size"] != len(data)+ or asset.get("digest") != digest+ ):+ raise ValueError(f"Staged asset failed verification: {asset['name']}")+ self.validate(source, dist, version)+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--repository", required=True)+ parser.add_argument("--commit", required=True)+ args = parser.parse_args()+ try:+ Publisher(args.repository).publish(args.commit)+ except (ValueError, KeyError, OSError, subprocess.CalledProcessError) as error:+ print(f"Release failed: {error}", file=sys.stderr)+ if isinstance(error, subprocess.CalledProcessError):+ print(error.stderr, file=sys.stderr)+ return 1+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/validate_release.py b/scripts/validate_release.pyindex 02f80297..69274dce 100644--- a/scripts/validate_release.py+++ b/scripts/validate_release.py@@ -2,6 +2,7 @@import argparseimport configparser+import reimport subprocessimport tarfileimport tomllib@@ -16,11 +17,17 @@ def require_files(names: set[str], expected: set[str]) -> None:raise ValueError("Missing release files: " + ", ".join(sorted(missing)))-def validate(directory: Path) -> None:+def validate(directory: Path, version: str) -> None:project = tomllib.loads(Path("pyproject.toml").read_text(encoding="utf-8"))["project"]- name, version = project["name"], project["version"]+ name = project["name"]+ if not re.fullmatch(+ r"(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)", version+ ):+ raise ValueError("Expected a stable MAJOR.MINOR.PATCH release version")+ if "version" in project or "version" not in project.get("dynamic", []):+ raise ValueError("Release source must use dynamic version metadata")stem = f"{name.replace('-', '_')}-{version}"wheel_path = directory / f"{stem}-py3-none-any.whl"sdist_path = directory / f"{stem}.tar.gz"@@ -90,9 +97,10 @@ def validate(directory: Path) -> None:def main() -> int:parser = argparse.ArgumentParser(description=__doc__)parser.add_argument("directory", type=Path)+ parser.add_argument("--version", required=True)args = parser.parse_args()try:- validate(args.directory)+ validate(args.directory, args.version)except (ValueError,KeyError,diff --git a/tests/contracts/test_issue_form_version_validation.py b/tests/contracts/test_issue_form_version_validation.pyindex 4ac37c8c..2e797653 100644--- a/tests/contracts/test_issue_form_version_validation.py+++ b/tests/contracts/test_issue_form_version_validation.py@@ -3,7 +3,6 @@ import reimport shutilimport subprocessimport textwrap-import tomllibfrom pathlib import Pathfrom typing import Any@@ -62,7 +61,6 @@ def test_bug_form_requests_a_contained_version_or_none() -> None:assert "Run `fcc-server --version`" in formassert "include one version" in form- assert "`number.number.number` format" in formassert "enter `None`" in formassert 'placeholder: "The version is 1.22.333, or None"' in formassert "not installed" not in form@@ -165,39 +163,21 @@ def test_workflow_owns_one_idempotent_triage_state() -> None:assert "comments.find" in workflow-def test_workflow_reads_and_compares_the_default_branch_version() -> None:- workflow = WORKFLOW.read_text(encoding="utf-8")- pyproject = Path("pyproject.toml").read_text(encoding="utf-8")- expected = tomllib.loads(pyproject)["project"]["version"]- project_pattern = _workflow_pattern("projectVersionPattern")- function = _javascript_function("projectVersionFromToml")- scoped_project = (- "[tool.before]\nversion = \"99.0.0\"\n\n[project]\nversion = '1.2.3'\n"- )- commented_project = (- '[project]\nname = "demo"\nversion = "2.3.4" # current release\n'- )- missing_project_version = (- '[project]\nname = "demo"\n\n[[tool.items]]\nversion = "99.0.0"\n'- )- script = (- f"const projectVersionPattern = {json.dumps(project_pattern)};\n"- f"{function}\n"- "process.stdout.write(JSON.stringify(["- f"projectVersionFromToml({json.dumps(pyproject)}),"- f"projectVersionFromToml({json.dumps(scoped_project)}),"- f"projectVersionFromToml({json.dumps(commented_project)}),"- f"projectVersionFromToml({json.dumps(missing_project_version)})"- "]));"- )-- assert _run_javascript(script) == [expected, "1.2.3", "2.3.4", None]- assert "contents: read" in workflow- assert "github.rest.repos.getContent" in workflow- assert 'path: "pyproject.toml"' in workflow- assert "context.payload.repository.default_branch" in workflow- assert 'split(".").map((part) => BigInt(part))' in workflow- assert "isOlderVersion(reportedVersion, latestVersion)" in workflow+ "tag,expected",+ [+ ("v1.2.3", "1.2.3"),+ ("v10.0.0", "10.0.0"),+ ("1.2.3", None),+ ("v1.2.3rc1", None),+ ("v01.2.3", None),+ ("v1.2.3.4", None),+ ],+)+def test_release_tags_are_exact_stable_versions(tag, expected):+ pattern = _workflow_pattern("releaseVersionPattern")+ match = re.fullmatch(pattern, tag)+ assert (match[1] if match else None) == expecteddef test_outdated_version_comment_is_reconciled_across_edits() -> None:@@ -248,16 +228,9 @@ const github = {},},repos: {- getContent: async (args) => {- record("getContent", args);- const content = `[tool.before]\nversion = "99.0.0"\n\n[project]\nversion = '${latestVersion}' # current release\n`;- return {- data: {- type: "file",- encoding: "base64",- content: Buffer.from(content).toString("base64"),- },- };+ getLatestRelease: async (args) => {+ record("getLatestRelease", args);+ return { data: { tag_name: "v" + latestVersion, draft: false, prerelease: false } };},},},@@ -301,19 +274,16 @@ process.stdout.write(JSON.stringify({ calls, comments }));)calls = result["calls"]names = [call["name"] for call in calls]- content_reads = [call for call in calls if call["name"] == "getContent"]assert names.count("createComment") == 2assert names.count("updateComment") == 1assert names.count("deleteComment") == 3- assert names.count("getContent") == 4+ assert names.count("getLatestRelease") == 4assert names.count("getIssue") == 6assert names.count("getLabel") == 1assert names.count("addLabels") == 1assert names.count("removeLabel") == 2assert "createLabel" not in names- assert all(call["args"]["path"] == "pyproject.toml" for call in content_reads)- assert all(call["args"]["ref"] == "main" for call in content_reads)assert "`17.23.454`" in next(call["args"]["body"]for call in calls@@ -330,3 +300,87 @@ process.stdout.write(JSON.stringify({ calls, comments }));assert "cancel-in-progress: false" in workflowassert "github.rest.issues.update({" not in workflowassert 'state: "closed"' not in workflow++[email protected]("status,should_fail", [(404, False), (500, True)])+def test_release_lookup_distinguishes_no_release_from_failure(status, should_fail):+ source = f"return (async () => {{\n{_workflow_script()}\n}})();"+ harness = """+const run = new Function("github", "context", __SOURCE__);+const deleted = [];+const github = {+ paginate: async () => [{id: 42, user: {login: "github-actions[bot]"}, body: "<!-- fcc-version-outdated -->"}],+ rest: {+ issues: {+ get: async () => ({data: {labels: [], body: "### FCC version\\n\\n1.2.3"}}),+ deleteComment: async ({comment_id}) => deleted.push(comment_id),+ },+ repos: {getLatestRelease: async () => {throw {status: __STATUS__};}},+ },+};+let failed = false;+try {await run(github, {repo: {owner: "o", repo: "r"}, payload: {issue: {number: 1}}});}+catch {failed = true;}+process.stdout.write(JSON.stringify({failed, deleted}));+"""+ result = _run_javascript(+ harness.replace("__SOURCE__", json.dumps(source)).replace(+ "__STATUS__", str(status)+ )+ )+ assert result["failed"] is should_fail+ assert result["deleted"] == ([] if should_fail else [42])+++ "value",+ [+ "6.2.67.dev1+g2f30121c0",+ "6.2.67.dev0+g2f30121c0.d20260925",+ "6.2.67.dev1",+ "6.2.66+d20260925",+ ],+)+def test_development_versions_are_accepted_without_stable_release_comparison(value):+ assert _reported_version(f"free-claude-code {value}") == value+ source = f"return (async () => {{\n{_workflow_script()}\n}})();"+ harness = """+const run = new Function("github", "context", __SOURCE__);+const calls = [];+const github = {+ paginate: async () => [+ {id: 1, user: {login: "github-actions[bot]"}, body: "<!-- fcc-version-validator -->"},+ {id: 2, user: {login: "github-actions[bot]"}, body: "<!-- fcc-version-outdated -->"},+ ],+ rest: {+ issues: {+ get: async () => ({data: {labels: [{name: "needs-fcc-version"}], body: "### FCC version\\n\\nfree-claude-code " + __VERSION__}}),+ removeLabel: async () => calls.push("removeLabel"),+ deleteComment: async ({comment_id}) => calls.push(comment_id),+ },+ repos: {getLatestRelease: async () => {throw new Error("Development builds must not be compared as stable releases");}},+ },+};+await run(github, {repo: {owner: "o", repo: "r"}, payload: {issue: {number: 1}}});+process.stdout.write(JSON.stringify(calls));+"""+ result = _run_javascript(+ harness.replace("__SOURCE__", json.dumps(source)).replace(+ "__VERSION__", json.dumps(value)+ )+ )+ assert result == ["removeLabel", 1, 2]+++ "value",+ [+ "6.2.67.dev",+ "6.2.67.dev1+gwrong",+ "6.2.67.dev1+g123.extra",+ "6.2.67.dev1+g123.d2026",+ "6.2.67.dev1+g123 and 6.2.66",+ ],+)+def test_invalid_or_ambiguous_development_versions_are_rejected(value):+ assert _reported_version(value) is Nonediff --git a/tests/contracts/test_uv_policy.py b/tests/contracts/test_uv_policy.pyindex ae66e85d..086dc888 100644--- a/tests/contracts/test_uv_policy.py+++ b/tests/contracts/test_uv_policy.py@@ -9,6 +9,7 @@ CI_SETUP = Path(".github/actions/ci-environment/action.yml")UV_WORKFLOWS = (Path(".github/workflows/tests.yml"),Path(".github/workflows/post-merge.yml"),+ Path(".github/workflows/version-policy.yml"),)REQUIRED_TEST_RUNNERS = {"Linux": "ubuntu-latest",diff --git a/tests/core/test_version.py b/tests/core/test_version.pyindex 084409bb..dcd94adb 100644--- a/tests/core/test_version.py+++ b/tests/core/test_version.py@@ -1,7 +1,5 @@-import tomllibfrom importlib.metadata import PackageNotFoundErrorfrom importlib.metadata import version as distribution_version-from pathlib import Pathimport pytest@@ -33,10 +31,3 @@ def test_package_version_does_not_hide_invalid_installed_metadata(with pytest.raises(ValueError, match="invalid metadata"):version_module.package_version()---def test_project_release_version_matches_installed_metadata() -> None:- repo_root = Path(__file__).resolve().parents[2]- pyproject = tomllib.loads((repo_root / "pyproject.toml").read_text("utf-8"))-- assert pyproject["project"]["version"] == distribution_version("free-claude-code")diff --git a/tests/scripts/test_publish_release.py b/tests/scripts/test_publish_release.pynew file mode 100644index 00000000..05f0abd7--- /dev/null+++ b/tests/scripts/test_publish_release.py@@ -0,0 +1,264 @@+"""Release ordering and interrupted publication use real Git history."""++import hashlib+import json+from pathlib import Path+from typing import TypedDict++import pytest++from scripts import publish_release as publishing+from scripts.check_version_policy import next_version+from tests.scripts.test_version_policy import commit, git, write+++ "kind,expected", [("patch", "6.2.67"), ("minor", "6.3.0"), ("major", "7.0.0")]+)+def test_one_increment(kind, expected):+ assert next_version("6.2.66", kind) == expected+++def releases(tmp_path, monkeypatch):+ monkeypatch.chdir(tmp_path)+ git(tmp_path, "init", "-b", "main")+ write(tmp_path, "src/file.py", "base")+ base = commit(tmp_path)+ git(tmp_path, "tag", "v1.2.3")+ git(tmp_path, "update-ref", "refs/remotes/origin/main", base)+ state = FakeRemote(tmp_path)+ monkeypatch.setattr(publishing, "command", state.command)+ return tmp_path, state+++class Asset(TypedDict):+ name: str+ state: str+ size: int+ digest: str+++class Release(TypedDict):+ tag_name: str+ draft: bool+ prerelease: bool+ assets: list[Asset]+++class FakeRemote:+ def __init__(self, repo):+ self.repo = repo+ self.releases: dict[str, Release] = {+ "v1.2.3": {+ "tag_name": "v1.2.3",+ "draft": False,+ "prerelease": False,+ "assets": [],+ }+ }+ self.files = {}+ self.calls = []+ self.fail = None+ self.builds = 0+ self.uploaded = {}+ self.real_command = publishing.command++ def command(self, args, *, cwd=None):+ if "--repo" in args:+ args = args[: args.index("--repo")]+ self.calls.append(args)+ if args[0] == "git":+ if args[1] in {"fetch", "push"}:+ return ""+ return git(Path(cwd or self.repo), *args[1:])+ if args[:2] == ["gh", "api"]:+ return json.dumps([list(self.releases.values())])+ if args[:3] == ["gh", "release", "create"]:+ tag = args[3]+ self.releases[tag] = {+ "tag_name": tag,+ "draft": True,+ "prerelease": False,+ "assets": [],+ }+ elif args[:3] == ["gh", "release", "upload"]:+ tag = args[3]+ for filename in args[4:]:+ file = Path(filename)+ data = file.read_bytes()+ self.files[tag, file.name] = data+ self.releases[tag]["assets"].append(+ {+ "name": file.name,+ "state": "uploaded",+ "size": len(data),+ "digest": "sha256:" + hashlib.sha256(data).hexdigest(),+ }+ )+ if self.fail == "stage":+ self.fail = None+ raise RuntimeError("interrupted staging")+ elif args[:3] == ["gh", "release", "delete-asset"]:+ tag, name = args[3:5]+ self.releases[tag]["assets"] = [+ a for a in self.releases[tag]["assets"] if a["name"] != name+ ]+ self.files.pop((tag, name), None)+ elif args[:3] == ["gh", "release", "download"]:+ tag = args[3]+ dest = Path(args[args.index("--dir") + 1])+ for asset in self.releases[tag]["assets"]:+ (dest / asset["name"]).write_bytes(self.files[tag, asset["name"]])+ elif args[:3] == ["gh", "release", "edit"]:+ if self.fail == "finalize":+ self.fail = None+ raise RuntimeError("interrupted finalization")+ self.releases[args[3]]["draft"] = False+ elif args[:2] == ["uv", "build"]:+ self.builds += 1+ assert cwd is not None+ version = git(Path(cwd), "describe", "--tags", "--exact-match")[1:]+ out = Path(args[args.index("--out-dir") + 1])+ for name in publishing.distribution_names(version):+ (out / name).write_bytes(f"build {self.builds}: {name}".encode())+ elif args[:2] == ["uv", "publish"]:+ for file in map(Path, args[4:]):+ data = file.read_bytes()+ if file.name in self.uploaded:+ assert self.uploaded[file.name] == data+ self.uploaded[file.name] = data+ if self.fail == "publish":+ self.fail = None+ raise RuntimeError("interrupted publication")+ elif args[0] == publishing.sys.executable:+ pass # Archive validation is exercised separately using real archives.+ else:+ raise AssertionError(args)+ return ""++ def advance(self, title="patch: Change", path="src/file.py"):+ write(self.repo, path, title)+ head = commit(self.repo, title)+ git(self.repo, "update-ref", "refs/remotes/origin/main", head)+ return head++ def publisher(self):+ return publishing.Publisher("owner/repo")+++def test_nonrelease_never_allocates_or_builds(releases):+ _, remote = releases+ head = remote.advance("Explain usage", "README.md")+ remote.publisher().publish(head)+ assert remote.builds == 0+ assert not any(c[:2] == ["git", "push"] for c in remote.calls)++[email protected]("failure", ["stage", "publish", "finalize"])+def test_retries_keep_version_and_published_bytes(releases, failure):+ repo, remote = releases+ head = remote.advance()+ remote.fail = failure+ with pytest.raises(RuntimeError):+ remote.publisher().publish(head)+ first_uploaded = dict(remote.uploaded)+ assert remote.releases["v1.2.4"]["draft"]+ remote.publisher().publish(head)+ assert not remote.releases["v1.2.4"]["draft"]+ assert git(repo, "rev-parse", "v1.2.4") == head+ assert remote.builds == (2 if failure == "stage" else 1)+ assert all(remote.uploaded[name] == value for name, value in first_uploaded.items())+ builds = remote.builds+ remote.publisher().publish(head)+ assert remote.builds == builds+++def test_later_commit_waits_even_if_previous_failed_before_tag(releases):+ _, remote = releases+ first = remote.advance()+ second = remote.advance("minor: Second")+ with pytest.raises(ValueError, match=first):+ remote.publisher().publish(second)+ remote.publisher().publish(first)+ remote.publisher().publish(second)+ assert not remote.releases["v1.3.0"]["draft"]+++def test_later_commit_waits_for_draft_and_old_retry_is_noop(releases):+ _, remote = releases+ first = remote.advance()+ remote.fail = "publish"+ with pytest.raises(RuntimeError):+ remote.publisher().publish(first)+ second = remote.advance("major: Second")+ with pytest.raises(ValueError, match=r"v1\.2\.4"):+ remote.publisher().publish(second)+ remote.publisher().publish(first)+ remote.publisher().publish(second)+ calls = len(remote.calls)+ remote.publisher().publish(first)+ assert not any(c[:3] == ["gh", "release", "edit"] for c in remote.calls[calls:])+++def test_tag_collision_and_extra_target_tag_are_rejected(releases):+ repo, remote = releases+ head = remote.advance()+ git(repo, "tag", "v1.2.4", "v1.2.3")+ with pytest.raises(ValueError):+ remote.publisher().publish(head)+ git(repo, "tag", "-d", "v1.2.4")+ git(repo, "tag", "v9.0.0", head)+ with pytest.raises(ValueError, match="another version"):+ remote.publisher().publish(head)+++def test_target_must_be_main_ancestor(releases):+ repo, remote = releases+ git(repo, "checkout", "-b", "other")+ write(repo, "src/other.py", "other")+ head = commit(repo, "patch: Other")+ with pytest.raises(ValueError, match="main"):+ remote.publisher().publish(head)+++def test_malformed_or_bypassed_title_cannot_publish(releases):+ _, remote = releases+ head = remote.advance("Oops")+ with pytest.raises(ValueError, match="require"):+ remote.publisher().publish(head)+++def test_reserved_tag_and_missing_draft_can_resume(releases):+ repo, remote = releases+ head = remote.advance()+ git(repo, "tag", "v1.2.4", head)+ remote.publisher().publish(head)+ assert remote.builds == 1+ assert not remote.releases["v1.2.4"]["draft"]+++def test_staged_bytes_are_verified_before_any_retry_upload(releases):+ _, remote = releases+ head = remote.advance()+ remote.fail = "publish"+ with pytest.raises(RuntimeError):+ remote.publisher().publish(head)+ name = publishing.distribution_names("1.2.4")[0]+ remote.files["v1.2.4", name] = b"corrupted"+ before = len(remote.calls)+ with pytest.raises(ValueError, match="verification"):+ remote.publisher().publish(head)+ assert not any(c[:2] == ["uv", "publish"] for c in remote.calls[before:])+++def test_no_release_does_not_wait_for_an_unfinished_release(releases):+ _, remote = releases+ first = remote.advance()+ remote.fail = "publish"+ with pytest.raises(RuntimeError):+ remote.publisher().publish(first)+ docs = remote.advance("Explain the release", "README.md")+ before = remote.builds+ remote.publisher().publish(docs)+ assert remote.builds == beforediff --git a/tests/scripts/test_release_package.py b/tests/scripts/test_release_package.pyindex 38293376..ab0bcde3 100644--- a/tests/scripts/test_release_package.py+++ b/tests/scripts/test_release_package.py@@ -20,7 +20,7 @@ def release(tmp_path):repo.mkdir()git(repo, "init")files = {- "pyproject.toml": '[project]\nname="free-claude-code"\nversion="1.2.3"\n[project.scripts]\nfcc-server="free_claude_code.cli:serve"\n[project.gui-scripts]\nfcc-desktop="free_claude_code.desktop:launch"\n',+ "pyproject.toml": '[project]\nname="free-claude-code"\ndynamic=["version"]\n[project.scripts]\nfcc-server="free_claude_code.cli:serve"\n[project.gui-scripts]\nfcc-desktop="free_claude_code.desktop:launch"\n',"README.md": "readme","LICENSE": "license","scripts/update/fcc-update": "#!/bin/sh\n",@@ -71,7 +71,7 @@ def validate(release, tmp_path):info.size = len(data)archive.addfile(info, io.BytesIO(data))return subprocess.run(- [sys.executable, str(VALIDATOR), str(dist)],+ [sys.executable, str(VALIDATOR), str(dist), "--version", "1.2.3"],cwd=repo,capture_output=True,text=True,diff --git a/tests/scripts/test_release_workflow.py b/tests/scripts/test_release_workflow.pyindex d0facb74..b7556813 100644--- a/tests/scripts/test_release_workflow.py+++ b/tests/scripts/test_release_workflow.py@@ -1,25 +1,24 @@-"""Release decisions and workflow permissions are explicit contracts."""+"""Workflow events, checkout identity and publishing privileges are contracts."""-import os-import subprocess-import sys+import shlexfrom pathlib import Pathimport pytestimport yaml-from tests.scripts.test_version_policy import commit, git, version, write+from tests.scripts.test_version_policy import commit, git, writeROOT = Path(__file__).resolve().parents[2]-WORKFLOW = ROOT / ".github/workflows/post-merge.yml"-def workflow():- return yaml.safe_load(WORKFLOW.read_text(encoding="utf-8"))+def load(name):+ return yaml.safe_load(+ (ROOT / ".github/workflows" / name).read_text(encoding="utf-8")+ )-def test_post_merge_serializes_runs_and_separates_publish_permissions():- config = workflow()+def test_post_merge_serializes_and_limits_publish_permissions():+ config = load("post-merge.yml")assert config["concurrency"] == {"group": "post-merge-main","cancel-in-progress": False,@@ -27,7 +26,7 @@ def test_post_merge_serializes_runs_and_separates_publish_permissions():}assert len(config["jobs"]) == 2cache = config["jobs"]["warm-dependency-cache"]- assert {entry["os"] for entry in cache["strategy"]["matrix"]["include"]} == {+ assert {e["os"] for e in cache["strategy"]["matrix"]["include"]} == {"Linux","Windows","macOS",@@ -35,73 +34,103 @@ def test_post_merge_serializes_runs_and_separates_publish_permissions():publish = config["jobs"]["publish"]assert "needs" not in publishassert publish["environment"] == "pypi"- assert publish["permissions"] == {"contents": "read", "id-token": "write"}+ assert publish["permissions"] == {"contents": "write", "id-token": "write"}assert cache["permissions"] == {"contents": "read"}for job in (cache, publish):assert job["if"] == "github.ref == 'refs/heads/main'"checkout = next(- step- for step in job["steps"]- if step.get("uses", "").startswith("actions/checkout@")+ s for s in job["steps"] if s.get("uses", "").startswith("actions/checkout@"))assert checkout["with"]["ref"] == "${{ github.sha }}"- for name in ("Build and validate release", "Publish release"):- step = next(step for step in publish["steps"] if step.get("name") == name)- assert step["if"] == "steps.release.outputs.changed == 'true'"+ assert checkout["with"]["fetch-depth"] == 0+ step = next(s for s in publish["steps"] if s.get("name") == "Publish release")+ assert step["env"]["RELEASE_COMMIT"] == "${{ inputs.release_commit || github.sha }}"+ assert "-m scripts.publish_release" in step["run"][email protected]("bump", [False, True])[email protected]("manual", [False, True])-def test_release_detection_uses_the_triggering_revision(tmp_path, bump, manual):- git(tmp_path, "init", "-b", "main")- version(tmp_path, "1.2.3")- before = commit(tmp_path)- version(tmp_path, "1.2.4" if bump else "1.2.3")- write(tmp_path, "README.md", "changed\n")- head = commit(tmp_path)- # A later checkout/commit must not change the queued run's release decision.- version(tmp_path, "9.0.0")- commit(tmp_path)- steps = workflow()["jobs"]["publish"]["steps"]- run = next(step["run"] for step in steps if step.get("id") == "release")- source = run.split("<<'PY'\n", 1)[1].rsplit("\nPY", 1)[0]- output = tmp_path / "outputs"- result = subprocess.run(- [sys.executable, "-c", source],- cwd=tmp_path,- env=os.environ- | {- "BEFORE_SHA": "" if manual else before,- "HEAD_SHA": head,- "GITHUB_OUTPUT": str(output),- },- capture_output=True,- text=True,- check=False,+def test_title_edits_only_trigger_the_separate_required_check():+ policy = load("version-policy.yml")+ tests = load("tests.yml")+ assert set(policy[True]) == {"pull_request"}+ assert set(policy[True]["pull_request"]["types"]) == {+ "opened",+ "synchronize",+ "reopened",+ "edited",+ "ready_for_review",+ }+ assert tests[True]["pull_request"] is None+ assert policy["concurrency"]["group"] != tests["concurrency"]["group"]+ assert "version-policy" not in tests["jobs"]+ job = policy["jobs"]["version-policy"]+ assert job["name"] == "Version policy"+ assert job["permissions"] == {"contents": "read", "pull-requests": "read"}+ checkout = next(+ s for s in job["steps"] if s.get("uses", "").startswith("actions/checkout@"))- assert result.returncode == 0, result.stdout + result.stderr- assert output.read_text().strip() == f"changed={str(bump).lower()}"+ assert checkout["with"]["ref"] == "${{ github.event.pull_request.head.sha }}"+ assert checkout["with"]["fetch-depth"] == 0+ current = next(+ s for s in job["steps"] if s.get("name") == "Read current pull request"+ )+ assert 'gh api "repos/$PR_REPOSITORY/pulls/$PR_NUMBER"' in current["run"]+ check = next(s for s in job["steps"] if s.get("name") == "Check version policy")+ assert "--pr-json" in check["run"]+ assert "title" not in check["env"]-def test_version_check_receives_pr_base_and_head_without_publish_permission():- config = yaml.safe_load(- (ROOT / ".github/workflows/tests.yml").read_text(encoding="utf-8")- )- assert set(config[True]) == {"pull_request"}- job = config["jobs"]["version-policy"]- checkout = next(- step- for step in job["steps"]- if step.get("uses", "").startswith("actions/checkout@")+def test_all_project_setup_jobs_have_history_and_fetch_canonical_tags():+ for filename in ("tests.yml", "version-policy.yml", "post-merge.yml"):+ for job in load(filename)["jobs"].values():+ if any(+ s.get("uses") == "./.github/actions/ci-environment"+ for s in job["steps"]+ ):+ checkout = next(+ s+ for s in job["steps"]+ if s.get("uses", "").startswith("actions/checkout@")+ )+ assert checkout["with"]["fetch-depth"] == 0+ setup = yaml.safe_load(+ (ROOT / ".github/actions/ci-environment/action.yml").read_text())- assert checkout["with"]["ref"] == "${{ github.event.pull_request.head.sha }}"- assert job["name"] == "Version policy"- assert job["permissions"] == {"contents": "read"}- step = next(- step for step in job["steps"] if step.get("name") == "Check version policy"+ fetch = setup["runs"]["steps"][0]+ assert fetch["env"]["CI_REPOSITORY"] == "${{ github.repository }}"++[email protected]("conflicting_tag", [False, True])+def test_ci_tag_fetch_uses_only_canonical_tags(tmp_path, conflicting_tag):+ upstream = tmp_path / "upstream.git"+ upstream.mkdir()+ git(upstream, "init", "-b", "main")+ write(upstream, "file", "release")+ released = commit(upstream)+ git(upstream, "tag", "-a", "v1.2.3", "-m", "release")+ checkout = tmp_path / "fork"+ git(tmp_path, "clone", str(upstream), str(checkout))+ write(checkout, "file", "pull request")+ head = commit(checkout)+ git(checkout, "tag", "v99.0.0")+ if conflicting_tag:+ git(checkout, "tag", "-f", "v1.2.3")+ write(upstream, "file", "new release")+ latest = commit(upstream)+ git(upstream, "tag", "v1.2.4")++ setup = yaml.safe_load(+ (ROOT / ".github/actions/ci-environment/action.yml").read_text())- assert step["env"] == {- "BASE_SHA": "${{ github.event.pull_request.base.sha }}",- "HEAD_SHA": "${{ github.event.pull_request.head.sha }}",- }- assert '--base "$BASE_SHA" --head "$HEAD_SHA"' in step["run"]+ command = shlex.split(setup["runs"]["steps"][0]["run"])+ command = [+ arg.replace("$CI_SERVER/$CI_REPOSITORY.git", upstream.as_posix())+ for arg in command+ ]+ assert command[0] == "git"+ for _ in range(2):+ git(checkout, *command[1:])+ assert git(checkout, "tag", "--list").splitlines() == ["v1.2.3", "v1.2.4"]+ assert git(checkout, "rev-parse", "v1.2.3^{}") == released+ assert git(checkout, "rev-parse", "v1.2.4") == latest+ assert git(checkout, "rev-parse", "HEAD") == head+ assert git(checkout, "status", "--porcelain") == ""diff --git a/tests/scripts/test_version_policy.py b/tests/scripts/test_version_policy.pyindex bcbbb5b3..425460f0 100644--- a/tests/scripts/test_version_policy.py+++ b/tests/scripts/test_version_policy.py@@ -1,4 +1,4 @@-"""Exercise version policy against real, isolated Git history."""+"""Release intent is validated against committed paths, not edited numbers."""import osimport subprocess@@ -11,7 +11,7 @@ CHECKER = Path(__file__).resolve().parents[2] / "scripts/check_version_policy.pydef git(repo: Path, *args: str) -> str:- result = subprocess.run(+ return subprocess.run(["git", "-C", str(repo), *args],check=True,capture_output=True,@@ -25,8 +25,7 @@ def git(repo: Path, *args: str) -> str:"GIT_COMMITTER_NAME": "Test","GIT_COMMITTER_EMAIL": "[email protected]",},- )- return result.stdout.strip()+ ).stdout.strip()def write(repo: Path, path: str, content: str) -> None:@@ -35,22 +34,9 @@ def write(repo: Path, path: str, content: str) -> None:target.write_text(content, encoding="utf-8")-def version(repo: Path, value: str, lock: str | None = None) -> None:- write(- repo,- "pyproject.toml",- f'[project]\nname = "free-claude-code"\nversion = "{value}"\n',- )- write(- repo,- "uv.lock",- f'[[package]]\nname = "free-claude-code"\nversion = "{lock or value}"\nsource = {{ editable = "." }}\n',- )---def commit(repo: Path) -> str:+def commit(repo: Path, title: str = "test change") -> str:git(repo, "add", ".")- git(repo, "commit", "--no-gpg-sign", "-m", "test change")+ git(repo, "commit", "--no-gpg-sign", "-m", title)return git(repo, "rev-parse", "HEAD")@@ -58,14 +44,32 @@ def commit(repo: Path) -> str:def history(tmp_path):git(tmp_path, "init", "-b", "main")git(tmp_path, "config", "core.autocrlf", "false")- version(tmp_path, "1.2.3")+ write(+ tmp_path,+ "pyproject.toml",+ '[project]\nname="free-claude-code"\ndynamic=["version"]\n',+ )+ write(+ tmp_path,+ "uv.lock",+ '[[package]]\nname="free-claude-code"\nsource={editable="."}\n',+ )write(tmp_path, "src/file.py", "original\n")return tmp_path, commit(tmp_path)-def check(repo: Path, base: str) -> subprocess.CompletedProcess[str]:+def check(repo: Path, base: str, title: str) -> subprocess.CompletedProcess[str]:return subprocess.run(- [sys.executable, str(CHECKER), "--base", base, "--head", "HEAD"],+ [+ sys.executable,+ str(CHECKER),+ "--base",+ base,+ "--head",+ "HEAD",+ "--title",+ title,+ ],cwd=repo,capture_output=True,text=True,@@ -84,162 +88,125 @@ def check(repo: Path, base: str) -> subprocess.CompletedProcess[str]:"uv.lock",],)[email protected]("bump", [False, True])-def test_release_changes_require_increase(history, path, bump):- repo, base = history- if bump:- version(repo, "1.2.4")- if path in {"pyproject.toml", "uv.lock"}:- with (repo / path).open("a", encoding="utf-8") as stream:- stream.write("# non-version change\n")- else:- write(repo, path, "changed\n")- commit(repo)- result = check(repo, base)- assert (result.returncode == 0) is bump, result.stdout + result.stderr- assert path in result.stdout--@pytest.mark.parametrize(- "path",+ "title,allowed",[- "README.md",- "tests/test_example.py",- ".github/workflows/ci.yml",- "scripts-other/a.py",+ ("patch: Fix it", True),+ ("minor: Add it", True),+ ("major: Replace it", True),+ ("Fix it", False),],)[email protected]("bump", [False, True])-def test_excluded_only_changes_forbid_increase(history, path, bump):- repo, base = history- if bump:- version(repo, "1.2.4")- write(repo, path, "documentation\n")- commit(repo)- result = check(repo, base)- assert (result.returncode == 0) is not bump, result.stdout + result.stderr---def test_version_only_change_does_not_justify_itself(history):+def test_release_inputs_require_prefix(history, path, title, allowed):repo, base = history- version(repo, "1.2.4")+ target = repo / path+ write(repo, path, (target.read_text() if target.exists() else "") + "\n# change\n")commit(repo)- result = check(repo, base)- assert result.returncode != 0- assert "without release changes" in result.stdout+ result = check(repo, base, title)+ assert (result.returncode == 0) is allowed, result.stdout + result.stderr@pytest.mark.parametrize(- "value,allowed",- [- ("1.2.4", True),- ("1.3.0", True),- ("2.0.0", True),- ("1.2.5", False),- ("1.4.0", False),- ("3.0.0", False),- ("1.3.1", False),- ("2.1.0", False),- ("2.0.1", False),- ("1.2.4rc1", False),- ("1.2.4.post1", False),- ("1.2.4.dev1", False),- ("1.2.4+local", False),- ("1!1.2.4", False),- ("1.2.4.0", False),- ("v1.2.4", False),- ("01.2.4", False),- ],+ "title",+ ["patch: Missing release", "minor: Missing release", "major: Missing release"],)-def test_release_requires_exactly_one_version_increment(history, value, allowed):+def test_nonrelease_changes_forbid_prefix(history, title):repo, base = history- version(repo, value)- write(repo, "src/file.py", "changed\n")+ write(repo, "README.md", "docs")commit(repo)- result = check(repo, base)- assert (result.returncode == 0) is allowed, result.stdout + result.stderr--[email protected]("final_version,allowed", [("1.2.4", True), ("1.2.5", False)])-def test_multiple_pr_commits_share_one_bump(history, final_version, allowed):- repo, base = history- version(repo, "1.2.4")- write(repo, "src/file.py", "first change\n")- commit(repo)- version(repo, final_version)- write(repo, "src/file.py", "second change\n")- commit(repo)- result = check(repo, base)- assert (result.returncode == 0) is allowed, result.stdout + result.stderr+ assert check(repo, base, title).returncode != 0@pytest.mark.parametrize(- "value,lock", [("1.2.2", None), ("1.2.4", "1.2.3"), ("invalid", None)]+ "title",+ [+ "Patch: Change",+ " patch: Change",+ "patch:Change",+ "patch: Change",+ "patch:\tChange",+ "patch: ",+ "patch : Change",+ "major\uff1a Change",+ ],)-def test_invalid_or_inconsistent_versions_fail(history, value, lock):+def test_malformed_release_title_rejected(history, title):repo, base = history- version(repo, value, lock)- write(repo, "src/file.py", "changed\n")+ write(repo, "src/file.py", "change")commit(repo)- assert check(repo, base).returncode != 0+ assert check(repo, base, title).returncode != 0@pytest.mark.parametrize("move", [False, True])-def test_deleting_or_moving_out_of_release_directory_requires_bump(history, move):+def test_delete_or_move_out_counts_as_release(history, move):repo, base = historyif move:- (repo / "src/file.py").rename(repo / "file with spaces.py")+ (repo / "src/file.py").rename(repo / "outside.py")else:(repo / "src/file.py").unlink()commit(repo)- result = check(repo, base)- assert result.returncode != 0- assert "src/file.py" in result.stdout+ assert check(repo, base, "Docs").returncode != 0+ assert check(repo, base, "patch: Remove file").returncode == 0-def test_other_lock_package_version_is_a_release_change(history):- repo, _ = history- with (repo / "uv.lock").open("a", encoding="utf-8") as stream:- stream.write('[[package]]\nname = "other"\nversion = "1.0"\n')+def test_unrelated_main_and_dirty_files_do_not_change_pr_classification(history):+ repo, original = history+ write(repo, "src/main.py", "main")base = commit(repo)- lock = repo / "uv.lock"- lock.write_text(lock.read_text().replace('version = "1.0"', 'version = "2.0"'))+ git(repo, "checkout", "-b", "docs", original)+ write(repo, "README.md", "docs")commit(repo)- result = check(repo, base)- assert result.returncode != 0- assert "uv.lock" in result.stdout+ write(repo, "src/file.py", "uncommitted")+ assert check(repo, base, "Explain setup").returncode == 0-def test_stale_release_cannot_reuse_new_main_version(history):- repo, original = history- version(repo, "1.2.4")- write(repo, "src/main.py", "main change\n")- base = commit(repo)- git(repo, "checkout", "-b", "pr", original)- version(repo, "1.2.4")- write(repo, "src/pr.py", "pr change\n")+def test_title_is_data_and_multiple_commits_have_one_intent(history):+ repo, base = history+ write(repo, "src/file.py", "one")commit(repo)- result = check(repo, base)- assert result.returncode != 0- assert "must increase" in result.stdout+ write(repo, "src/file.py", "two")+ commit(repo)+ assert check(repo, base, 'patch: $(echo unsafe) `literal` "quoted"').returncode == 0-def test_unrelated_main_changes_are_not_attributed_to_docs_pr(history):- repo, original = history- write(repo, "src/main.py", "main change\n")- base = commit(repo)- git(repo, "checkout", "-b", "pr", original)- write(repo, "README.md", "docs\n")+def test_manual_version_is_rejected(history):+ repo, base = history+ write(+ repo, "pyproject.toml", '[project]\nname="free-claude-code"\nversion="1.2.3"\n'+ )commit(repo)- result = check(repo, base)- assert result.returncode == 0, result.stdout + result.stderr+ assert check(repo, base, "patch: Manual version").returncode != 0++def test_pr_snapshot_uses_latest_title_and_rejects_stale_head(history, tmp_path):+ import json-def test_checker_reads_commits_not_uncommitted_files(history):repo, base = history- write(repo, "README.md", "docs\n")- commit(repo)- version(repo, "9.9.9")- write(repo, "src/file.py", "uncommitted\n")- result = check(repo, base)- assert result.returncode == 0, result.stdout + result.stderr+ write(repo, "src/file.py", "change")+ head = commit(repo)+ payload = tmp_path / "current-pr.json"+ payload.write_text(+ json.dumps(+ {"head": {"sha": head}, "base": {"sha": base}, "title": "patch: New title"}+ )+ )+ result = subprocess.run(+ [sys.executable, str(CHECKER), "--head", head, "--pr-json", str(payload)],+ cwd=repo,+ capture_output=True,+ text=True,+ )+ assert result.returncode == 0, result.stdout+ payload.write_text(+ json.dumps(+ {"head": {"sha": base}, "base": {"sha": base}, "title": "patch: New title"}+ )+ )+ result = subprocess.run(+ [sys.executable, str(CHECKER), "--head", head, "--pr-json", str(payload)],+ cwd=repo,+ capture_output=True,+ text=True,+ )+ assert result.returncode != 0+ assert "head changed" in result.stdoutdiff --git a/uv.lock b/uv.lockindex 489a472d..95eca9bc 100644--- a/uv.lock+++ b/uv.lock@@ -599,7 +599,6 @@ wheels = [[[package]]name = "free-claude-code"-version = "6.2.66"source = { editable = "." }dependencies = [{ name = "aiohttp" },