项目文件夹

文件
Ali Khokhar 85b601884d Remove legacy future annotation imports (#982)
## Problem

Python 3.14 provides native lazy annotations, but the codebase still
relied on legacy future annotation imports. Those imports also made
type-only import cycles easier to hide instead of fixing ownership
boundaries.

## Changes

| Before | After |
| --- | --- |
| Python files used `from __future__ import annotations`. | Python files
rely on Python 3.14 native lazy annotations. |
| Some runtime modules used `TYPE_CHECKING` or local imports for
required dependencies. | Runtime modules use top-level owner-module
imports with explicit boundaries. |
| Local and GitHub guardrails only rejected type ignore suppressions. |
Local and GitHub guardrails reject type ignore suppressions and legacy
future annotation imports. |
| Agent docs only documented the no-type-ignore rule. | Agent docs
document the Python 3.14 annotation and import-boundary rules. |

<!-- greptile_comment -->

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

This PR moves the codebase to Python 3.14 native lazy annotations. The
main changes are:

- Removed legacy `from __future__ import annotations` imports across
Python modules.
- Promoted selected runtime dependencies from `TYPE_CHECKING` or local
imports to explicit owner-module imports.
- Added local, GitHub, and contract-test guardrails to reject legacy
future annotation imports.
- Updated agent docs with the annotation and import-boundary rules.
- Bumped the package patch version for production-file changes.
</details>

<h3>Confidence Score: 5/5</h3>

Safe to merge with low risk.

The changes are mostly mechanical annotation cleanup with matching CI
and contract-test guardrails. Reviewed import-boundary updates did not
show a confirmed runtime cycle or dependency break.

No files require special attention.

<details><summary><h3><a href="https://www.greptile.com/trex"><img
alt="T-Rex"
src="https://greptile-static-assets.s3.amazonaws.com/trex/trex_green.svg"
height="20" align="absmiddle"></a> T-Rex Logs</h3></summary>

**What T-Rex did**
- Performed an end-to-end validation of the guardrail contract suite: an
environment check confirmed uv availability, a guardrail pytest run used
CPython 3.14.0 with 5 passing contract tests, 3 focused CI-script tests
passed, and the direct CI suppressions guardrail command (including the
legacy future-annotations grep) also passed.

<a
href="https://app.greptile.com/trex/runs/13303335/artifacts"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://greptile-static-assets.s3.amazonaws.com/badges/ViewAllArtifactsDark.svg?v=4"><source
media="(prefers-color-scheme: light)"
srcset="https://greptile-static-assets.s3.amazonaws.com/badges/ViewAllArtifacts.svg?v=4"><img
alt="View all artifacts"
src="https://greptile-static-assets.s3.amazonaws.com/badges/ViewAllArtifacts.svg?v=4"></picture></a>

<sub><a href="https://www.greptile.com/trex"><img alt="T-Rex"
src="https://greptile-static-assets.s3.amazonaws.com/trex/trex_green.svg"
height="14" align="absmiddle"></a> Ran code and verified through
T-Rex</sub>
</details>

<details open><summary><h3>Important Files Changed</h3></summary>

| Filename | Overview |
|----------|----------|
| api/runtime.py | Moves messaging, CLI manager, session, limiter, and
tree dependencies from local/type-checking imports to explicit top-level
owner-module imports. |
| messaging/platforms/telegram.py | Removes future annotations and
promotes Telegram SDK type imports into the existing availability guard.
|
| messaging/platforms/telegram_inbound.py | Removes future annotations
and imports Telegram SDK types at module scope for inbound
normalization. |
| tests/contracts/test_import_boundaries.py | Adds an AST contract that
rejects legacy future annotation imports across Python files. |
| scripts/ci.sh | Extends the local suppression check to reject legacy
future annotation imports alongside type-ignore suppressions. |
| scripts/ci.ps1 | Mirrors the local PowerShell CI suppression check for
legacy future annotations. |
| .github/workflows/tests.yml | Renames and broadens the GitHub
guardrail job to reject both type suppressions and legacy future
annotations. |
| pyproject.toml | Bumps the patch version for production-file changes.
|

</details>

<details open><summary><h3>Sequence Diagram</h3></summary>

<a href="#gh-light-mode-only">

```mermaid
%%{init: {'theme': 'neutral'}}%%
sequenceDiagram
participant Dev as Developer/CI
participant Guard as Suppression guard
participant AST as Import-boundary contract test
participant Py as Python modules

Dev->>Guard: Run local/GitHub suppression check
Guard->>Py: "Scan *.py for type ignores and future annotations"
Guard-->>Dev: Fail if legacy annotation import remains
Dev->>AST: Run pytest contract tests
AST->>Py: Parse imports with ast
AST-->>Dev: Assert no future annotations/import-boundary violations
Py-->>Dev: Use Python 3.14 native lazy annotations
```

</a>
<a href="#gh-dark-mode-only">

```mermaid
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
sequenceDiagram
participant Dev as Developer/CI
participant Guard as Suppression guard
participant AST as Import-boundary contract test
participant Py as Python modules

Dev->>Guard: Run local/GitHub suppression check
Guard->>Py: "Scan *.py for type ignores and future annotations"
Guard-->>Dev: Fail if legacy annotation import remains
Dev->>AST: Run pytest contract tests
AST->>Py: Parse imports with ast
AST-->>Dev: Assert no future annotations/import-boundary violations
Py-->>Dev: Use Python 3.14 native lazy annotations
```

</a>
</details>

<sub>Reviews (2): Last reviewed commit: ["Remove legacy future
annotations
import"](https://github.com/alishahryar1/free-claude-code/commit/6e6cda69da243bbdb92831207aecb3731ad469f8)
| [Re-trigger
Greptile](https://app.greptile.com/api/retrigger?id=41875785)</sub>

<!-- /greptile_comment -->
2026-07-04 21:41:51 -07:00

308 行
8.8 KiB
Python

import os
import shutil
import subprocess
from pathlib import Path
import pytest
def _repo_root() -> Path:
return Path(__file__).resolve().parents[2]
def _script_text(name: str) -> str:
return (_repo_root() / "scripts" / name).read_text(encoding="utf-8")
def _braced_body(text: str, declaration: str) -> str:
start = text.index(declaration)
brace_start = text.index("{", start)
depth = 0
for index, char in enumerate(text[brace_start:], start=brace_start):
if char == "{":
depth += 1
elif char == "}":
depth -= 1
if depth == 0:
return text[brace_start + 1 : index]
raise AssertionError(f"Unclosed function body for {declaration}")
def _path_without_uv() -> str:
uv_names = ("uv", "uv.exe", "uv.cmd", "uv.bat")
entries = []
for raw_entry in os.environ.get("PATH", "").split(os.pathsep):
if not raw_entry:
continue
entry = Path(raw_entry)
if any((entry / name).exists() for name in uv_names):
continue
entries.append(raw_entry)
return os.pathsep.join(entries)
def _shell_interpreter() -> str:
sh = shutil.which("sh")
if sh is None:
pytest.skip("sh is not available on this platform")
return sh
def _powershell_interpreter() -> str:
pwsh = shutil.which("pwsh") or shutil.which("powershell")
if pwsh is None:
pytest.skip("PowerShell is not available on this platform")
return pwsh
def test_ci_sh_runs_ci_checks_in_order() -> None:
text = _script_text("ci.sh")
legacy_future_import = "from __future__ import " + "annotations"
assert 'CHECK_ORDER="suppressions ruff-format ruff-check ty pytest"' in text
assert "grep -rE" in text
assert "Fix the underlying type/import issue instead" in text
assert legacy_future_import in text
assert "legacy future annotations are not allowed" in text
assert "--exclude-dir=.venv" in text
assert "--exclude-dir=.git" in text
assert "uv run ruff format" in text
assert "uv run ruff format --check" not in text
assert "uv run ruff check --fix" in text
assert "uv run ty check" in text
assert "uv run pytest -v --tb=short" in text
assert "--only" in text
assert "--skip" in text
assert "--dry-run" in text
assert "uv is required but was not found on PATH" in text
assert "npm" not in text
assert "smoke/" not in text
assert "uv self update" not in text
def test_ci_sh_dry_run_does_not_require_uv() -> None:
result = subprocess.run(
[
_shell_interpreter(),
str(_repo_root() / "scripts" / "ci.sh"),
"--only",
"pytest",
"--dry-run",
],
cwd=_repo_root(),
env={**os.environ, "PATH": _path_without_uv()},
text=True,
capture_output=True,
check=False,
)
assert result.returncode == 0
assert "+ uv run pytest -v --tb=short" in result.stdout
assert "uv is required" not in result.stderr
@pytest.mark.parametrize(
("check_id", "command"),
[
("ruff-format", "+ uv run ruff format"),
("ruff-check", "+ uv run ruff check --fix"),
],
)
def test_ci_sh_dry_run_prints_local_ruff_repair_commands(
check_id: str, command: str
) -> None:
result = subprocess.run(
[
_shell_interpreter(),
str(_repo_root() / "scripts" / "ci.sh"),
"--only",
check_id,
"--dry-run",
],
cwd=_repo_root(),
env={**os.environ, "PATH": _path_without_uv()},
text=True,
capture_output=True,
check=False,
)
assert result.returncode == 0
assert command in result.stdout
assert "uv is required" not in result.stderr
def test_ci_sh_suppression_only_does_not_require_uv() -> None:
result = subprocess.run(
[
_shell_interpreter(),
str(_repo_root() / "scripts" / "ci.sh"),
"--only",
"suppressions",
],
cwd=_repo_root(),
env={**os.environ, "PATH": _path_without_uv()},
text=True,
capture_output=True,
check=False,
)
assert result.returncode == 0
assert "Ban suppressions and legacy annotations" in result.stdout
assert "uv is required" not in result.stderr
def test_ci_sh_is_tracked_executable() -> None:
result = subprocess.run(
["git", "ls-files", "--stage", "scripts/ci.sh"],
cwd=_repo_root(),
text=True,
capture_output=True,
check=True,
)
assert result.stdout.startswith("100755 ")
def test_ci_sh_fail_fast_runs_checks_sequentially() -> None:
text = _script_text("ci.sh")
main = text[text.index('parse_args "$@"') :]
suppress_index = text.index("run_suppressions()")
ruff_format_index = text.index("run_ruff_format()")
ruff_check_index = text.index("run_ruff_check()")
ty_index = text.index("run_ty()")
pytest_index = text.index("run_pytest()")
assert (
suppress_index < ruff_format_index < ruff_check_index < ty_index < pytest_index
)
assert "for check_id in $CHECK_ORDER" in main
def test_ci_ps1_runs_ci_checks_in_order() -> None:
text = _script_text("ci.ps1")
legacy_future_import = "from __future__ import " + "annotations"
assert '"suppressions"' in text
assert '"ruff-format"' in text
assert '"ruff-check"' in text
assert '"ty"' in text
assert '"pytest"' in text
assert "Select-String -Pattern" in text
assert "Fix the underlying type/import issue instead" in text
assert legacy_future_import in text
assert "legacy future annotations are not allowed" in text
assert ".venv" in text
assert ".git" in text
assert '"run", "ruff", "format"' in text
assert '"format", "--check"' not in text
assert '"run", "ruff", "check", "--fix"' in text
assert '"-v", "--tb=short"' in text
assert "-Only" in text
assert "-Skip" in text
assert "-DryRun" in text
assert "uv is required but was not found on PATH" in text
assert "npm" not in text
assert "smoke/" not in text
assert "uv self update" not in text
def test_ci_ps1_dry_run_does_not_require_uv() -> None:
result = subprocess.run(
[
_powershell_interpreter(),
"-NoProfile",
"-File",
str(_repo_root() / "scripts" / "ci.ps1"),
"-Only",
"pytest",
"-DryRun",
],
cwd=_repo_root(),
env={**os.environ, "PATH": _path_without_uv()},
text=True,
capture_output=True,
check=False,
)
assert result.returncode == 0
assert "+ uv run pytest -v --tb=short" in result.stdout
assert "uv is required" not in result.stderr
@pytest.mark.parametrize(
("check_id", "command"),
[
("ruff-format", "+ uv run ruff format"),
("ruff-check", "+ uv run ruff check --fix"),
],
)
def test_ci_ps1_dry_run_prints_local_ruff_repair_commands(
check_id: str, command: str
) -> None:
result = subprocess.run(
[
_powershell_interpreter(),
"-NoProfile",
"-File",
str(_repo_root() / "scripts" / "ci.ps1"),
"-Only",
check_id,
"-DryRun",
],
cwd=_repo_root(),
env={**os.environ, "PATH": _path_without_uv()},
text=True,
capture_output=True,
check=False,
)
assert result.returncode == 0
assert command in result.stdout
assert "uv is required" not in result.stderr
def test_ci_ps1_suppression_only_does_not_require_uv() -> None:
result = subprocess.run(
[
_powershell_interpreter(),
"-NoProfile",
"-File",
str(_repo_root() / "scripts" / "ci.ps1"),
"-Only",
"suppressions",
],
cwd=_repo_root(),
env={**os.environ, "PATH": _path_without_uv()},
text=True,
capture_output=True,
check=False,
)
assert result.returncode == 0
assert "Ban suppressions and legacy annotations" in result.stdout
assert "uv is required" not in result.stderr
def test_ci_ps1_fail_fast_runs_checks_sequentially() -> None:
text = _script_text("ci.ps1")
assert "foreach ($checkId in $CheckOrder)" in text
assert "Invoke-SuppressionsCheck" in text
assert "Invoke-RuffFormatCheck" in text
assert "Invoke-RuffLintCheck" in text
assert "Invoke-TyCheck" in text
assert "Invoke-PytestCheck" in text
suppress_index = text.index("function Invoke-SuppressionsCheck")
ruff_format_index = text.index("function Invoke-RuffFormatCheck")
ruff_check_index = text.index("function Invoke-RuffLintCheck")
ty_index = text.index("function Invoke-TyCheck")
pytest_index = text.index("function Invoke-PytestCheck")
assert (
suppress_index < ruff_format_index < ruff_check_index < ty_index < pytest_index
)