Files
Ali KhokharandClaude Opus 5.5 3c83b78e20 patch: Fail type checks on Any returns, unknown returns and unknown attributes (#2607)
## Why

Pyrefly's strict preset leaves the Any checks off. Three of them cost
almost nothing to turn on: `no-any-return` (a function declared to
return a concrete type returns `Any`), `unknown-return-type` and
`unknown-attribute-type`. Together they report 22 sites. Each site is a
value whose type nobody checks.

The larger Any checks (`explicit-any`, `unknown-variable-type`,
`unknown-argument-type`, `partially-unknown-type`) are left for later.
`partially-unknown-type` waits for a Pyrefly release that types `async
def` coroutines (facebook/pyrefly#5720).

## How

- `pyproject.toml` turns on the three checks as errors.
- At JSON and SDK boundaries (`json.loads`, `response.json()`,
markdown-it, urllib, ruamel, `AsyncMock`), the value is assigned to an
annotated local before it is returned. This is the pattern
`catalog_http.py` and `managed/claude.py` already use.
- `ContinuationRequest` casts the Responses input the way its
neighbouring returns already do.
- The Vertex token provider only returns a cached Google token when it
is a non-empty `str`; google-auth leaves `token` untyped. A truthy
non-string token now goes through the refresh path, which already
rejects it.
- `openai_error_from_failure` builds the inner error directly instead of
wrapping it in an envelope and indexing it back out.
- The Codex smoke test types its event queue. That exposed two chained
`.get` calls on nested JSON, which now go through `object_payload`.
- The thread-dump pytest hook gets its generator return type.

🤖 Generated with [Claude Code](https://claude.com/claude-code)


<!-- greptile_comment -->

<!-- greptile_summary -->

<h2>Confidence Score: 5/5<a
href="https://app.greptile.com/api/retrigger?id=126409510&amp;sig=34d3ee34f8e7572fb1f0712bbd8a2cd8eb21f8ae5929a234a153aff3ca354635"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://greptile-static-assets.s3.amazonaws.com/badges/RetriggerDark.svg?v=2"><source
media="(prefers-color-scheme: light)"
srcset="https://greptile-static-assets.s3.amazonaws.com/badges/Retrigger.svg?v=2"><img
alt="Retrigger"
src="https://greptile-static-assets.s3.amazonaws.com/badges/Retrigger.svg?v=2"
align="right"></picture></a><a
href="https://app.greptile.com/-/switch-tenant?tenant=alishahryar1&amp;next=%2FAlishahryar1%2Ffree-claude-code%2Fpull%2F2607&amp;utm_source=greptile_review&amp;utm_medium=github&amp;utm_campaign=view_in_greptile"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://greptile-static-assets.s3.amazonaws.com/badges/ViewInGreptileDark.svg?v=2"><source
media="(prefers-color-scheme: light)"
srcset="https://greptile-static-assets.s3.amazonaws.com/badges/ViewInGreptile.svg?v=2"><img
alt="View in Greptile"
src="https://greptile-static-assets.s3.amazonaws.com/badges/ViewInGreptile.svg?v=2"
align="right"></picture></a></h2>

<!-- greptile-impact-verdict --> The PR appears safe to merge; no
actionable issues were found.

<details open><summary><h3>Summary</h3></summary>

The PR enables three stricter Pyrefly checks and adds types at JSON and
SDK boundaries.
- Pyrefly now flags unclear return and attribute types as errors.
- Vertex authentication reuses cached tokens only when they are
non-empty strings.
- OpenAI error responses now build their inner error details directly.

No actionable issues were found. Tests and type checks were not run.

Alishahryar1 explicitly described rejecting truthy non-string Vertex
tokens as intentional in the PR description.
</details>

<!-- greptile_confidence_score:5 -->

<sub>Reviews (1) · Last reviewed commit: ["Fail type checks on Any
returns,
unknown..."](https://github.com/alishahryar1/free-claude-code/commit/2d68438ff3fa6340f1eb8f0655118b07bb691939)
· [Reviewed by
Greptile](https://www.greptile.com/?utm_source=greptile_review&utm_medium=github&utm_campaign=review_public&utm_content=alishahryar1/free-claude-code)</sub>

<!-- /greptile_comment -->

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 00:51:50 -08:00

286 lines
10 KiB
Python

"""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 typing import Literal, NotRequired, Protocol, TypedDict, cast, overload
from .check_version_policy import (
VERSION,
changed_paths,
git,
next_version,
release_kind,
release_paths,
)
class _ReleaseAsset(TypedDict):
name: str
state: str
size: int
digest: NotRequired[str | None]
class _Release(TypedDict):
id: int
tag_name: str
prerelease: bool
draft: bool
assets: list[_ReleaseAsset]
class _ReleaseNotes(TypedDict):
name: str
body: str
# Reserve the version of the unpublished Windows signing draft.
WITHDRAWN_RELEASE = ("v6.19.38", "fda456aea40f7d3297003fafc710460afbb27cea")
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
def gh(self, *args: str) -> str:
return command(["gh", "release", *args, "--repo", self.repository])
@overload
def release_api(
self, suffix: Literal["/generate-notes"], *args: str
) -> _ReleaseNotes: ...
@overload
def release_api(self, suffix: int | Literal[""], *args: str) -> _Release: ...
def release_api(
self, suffix: int | Literal["", "/generate-notes"], *args: str
) -> _Release | _ReleaseNotes:
path = f"/{suffix}" if isinstance(suffix, int) else suffix
release: _Release | _ReleaseNotes = json.loads(
command(["gh", "api", f"repos/{self.repository}/releases{path}", *args])
)
return release
def releases(self) -> dict[str, _Release]:
pages: list[list[_Release]] = 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")
withdrawn_tag, withdrawn_commit = WITHDRAWN_RELEASE
if target == withdrawn_commit:
raise ValueError(f"Release {withdrawn_tag} was withdrawn")
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)
withdrawn_predecessor = (previous, tags[previous]) == WITHDRAWN_RELEASE
if (
not predecessor
or predecessor["prerelease"]
or (predecessor["draft"] and not withdrawn_predecessor)
):
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:
notes = self.release_api(
"/generate-notes",
"-f",
f"tag_name={tag}",
"-f",
f"previous_tag_name={previous}",
)
release = self.release_api(
"",
"-f",
f"tag_name={tag}",
"-f",
f"name={tag}",
"-f",
f"body={notes['body']}",
"-F",
"draft=true",
)
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, release["id"], 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(source / "scripts/validate_release.py"),
str(dist),
"--version",
version,
],
cwd=source,
)
def stage(
self, tag: str, release_id: int, version: str, source: Path, dist: Path
) -> None:
names = set(distribution_names(version))
assets = self.release_api(release_id)["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")
builder = source / "scripts/build_macos_launcher.py"
# Historical releases predate the native templates and retain their format.
if builder.is_file():
command([sys.executable, str(builder)], cwd=source)
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.release_api(release_id)["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)
class _TextProcessFailure(Protocol):
stderr: str | None
class _Arguments(argparse.Namespace):
repository: str
commit: str
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--repository", required=True)
parser.add_argument("--commit", required=True)
args = _Arguments()
parser.parse_args(namespace=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(cast(_TextProcessFailure, error).stderr, file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())