diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 2f41603..3744019 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -1,9 +1,9 @@ Describe the behavior change and why it is needed. -Validation: +- Report the verification command and result. For user-facing changes, include the + operation you exercised and its observed outcome. +- Identify the evidence used (fixture, configuration adapter or actual provider/client). + Include relevant client/protocol/model versions and any skipped checks. +- For a release, identify the commit and CI artifact containing the tested wheel and sdist. -- Commands/results, with simulated and real-provider evidence distinguished. -- Client/protocol/model versions if relevant. -- Remaining limitations or required manual checks. - -Do not include keys or unredacted private logs. An administrator code-owner review is required. +Keep keys and private logs out of the PR. An independent administrator reviews the change. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ff1e514..d5890ba 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -17,8 +17,8 @@ jobs: python: ['3.11', '3.14'] runs-on: ${{ matrix.os }} steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: ${{ matrix.python }} - run: python -m pip install . @@ -28,14 +28,22 @@ jobs: quality: runs-on: ubuntu-latest steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: '3.11' - - run: python -m pip install . -r requirements-dev.txt - - run: ruff check . - - run: ruff format --check . - - run: python -m build + - run: python -m pip install -e . -r requirements-dev.txt + - name: Verify source, installed wheel and native journal model + run: | + curl --fail --location --silent --show-error --retry 3 \ + https://github.com/tlaplus/tlaplus/releases/download/v1.7.4/tla2tools.jar -o "$RUNNER_TEMP/tla2tools.jar" + python scripts/verify.py --tlc-jar "$RUNNER_TEMP/tla2tools.jar" --dist-dir dist + - name: Archive checked wheel and source distribution + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: agent-connect-${{ github.sha }}-${{ github.run_attempt }} + path: dist/ + if-no-files-found: error magpie: runs-on: ubuntu-latest @@ -43,8 +51,8 @@ jobs: ITERACONNECT_HOME: ${{ github.workspace }}/.local/ci DO_NOT_TRACK: '1' steps: - - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: '3.11' - run: python -m pip install . diff --git a/.gitignore b/.gitignore index a82e44e..b34ee5b 100644 --- a/.gitignore +++ b/.gitignore @@ -11,3 +11,5 @@ dist/ reports/ .ruff_cache/ agent-connect.local.toml +.mypy_cache/ +.import_linter_cache/ diff --git a/AGENTS.md b/AGENTS.md index 20ffa8f..1ceae7b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,12 +1,13 @@ # Agent Connect development -This repository is independent of IteraCompute/LLMProxy. Do not change production gateway, -website or platform services as part of connector development. +Scope is this connector repository. Production gateway, website and platform services +belong in their own repositories. Use a feature branch and submit a PR for independent +administrator review. -- Python source is in `src/iteraconnect`; the runtime uses the standard library only. -- Use `python -m unittest discover -v`, Ruff check/format and `python -m build`. -- Optional real Magpie/native fixture tests are documented in `docs/testing.md`. -- The simple app stores keys only in ignored private local TOML; runtime provider profiles use environment references. Never print keys, request bodies or arbitrary client logs. -- Distinguish fixture tests, config adapter checks and actual provider/client acceptance. -- Preserve upstream MIT notices and pinned source/release provenance. -- Work on a feature branch and open a PR. Do not merge or bypass administrator review. +Run `python scripts/verify.py` before review. [Testing and release](docs/testing.md) +covers setup, the installed-wheel checks, the recovery model and release artifacts. + +- Keep credentials in ignored private local TOML or runtime environment references. + Never print keys, request bodies or arbitrary client logs. +- Preserve upstream MIT notices and pinned source and release provenance. +- Report fixture, configuration adapter and actual provider/client evidence separately. diff --git a/MANIFEST.in b/MANIFEST.in index c1a54f6..aa86cee 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -3,3 +3,5 @@ include start.py Start.command Start.bat config.example.toml recursive-include docs *.md recursive-include docs/images *.jpg recursive-include tests *.py +include scripts/verify.py +recursive-include verification *.cfg *.tla diff --git a/docs/testing.md b/docs/testing.md index f192f24..7439921 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -13,12 +13,49 @@ Tests deliberately distinguish three kinds of evidence: ```bash python -m pip install -e . -r requirements-dev.txt -python -m unittest discover -v -ruff check . -ruff format --check . -python -m build +python scripts/verify.py ``` +Run these commands from an activated Python 3.11+ virtual environment. The verifier runs +Ruff, mypy across the runtime (including unannotated function bodies), and the import layers +declared in `pyproject.toml`. New runtime modules must fit a layer. The configuration boundary +requires typed function signatures. A test scans static imports for the standard-library-only +runtime contract, including imports inside functions. + +The verifier then runs `python -m build`, installs the wheel built from the sdist into a fresh +environment, initializes a disposable CLI profile and reads it back. It runs unittest discovery +against that installation, including the loopback control panel, packaged web assets, fixture +provider probes and client config restoration. For a shorter edit cycle, run +`python -m unittest discover -v` against the editable installation. + +### Native configuration recovery model + +The TLA+ model covers one client file, an initial connection, reconnections, an interruption +between journaling and replacing the file, and a later external edit with a distinct digest. +TLC checks that the original image survives reconnection, a restore is enabled after an +interrupted write, and the adapter preserves that external edit. The model assumes serialized +operations and atomic single-file replacement. Concurrent external writers, interruptions +during disconnect, and filesystem durability are outside its scope. The Python regression in +`NativeEditorTests` injects a write failure into the real adapter and checks exact recovery for +both existing and absent files. + +CI runs the model on every PR. To reproduce this locally, install Java 11+ and download +`tla2tools.jar` from the pinned release. Run +`python scripts/verify.py --tlc-jar /path/to/tla2tools.jar`. The verifier checks its SHA-256 +before execution. [TLC release](https://github.com/tlaplus/tlaplus/releases/tag/v1.7.4) · +[Model and properties](../verification/NativeJournal.tla) + +### Release handoff + +Each successful quality job archives the exact sdist and wheel it tested, under +`agent-connect--` in GitHub Actions. For release, use the artifact from the +successful **push to protected main** for the reviewed commit. Check the commit SHA and +aggregate `checks` result before using that artifact. The PR run is available for review. +A local rehearsal can retain both artifacts in a new directory with +`python scripts/verify.py --tlc-jar /path/to/tla2tools.jar --dist-dir dist/candidate`. + +### Optional native and Magpie checks + For the actual Magpie engine, install the pinned binary, then set `ITERACONNECT_TEST_MAGPIE_BIN` to its absolute path: diff --git a/pyproject.toml b/pyproject.toml index f2f54d5..13832b6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -31,4 +31,35 @@ target-version = "py311" line-length = 100 [tool.ruff.lint] -select = ["E4", "E7", "E9", "F", "I"] +select = ["B", "E4", "E7", "E9", "F", "I", "PGH003", "PGH004", "RUF100"] + +[tool.mypy] +files = ["src/iteraconnect"] +python_version = "3.11" +check_untyped_defs = true +warn_unused_ignores = true +warn_redundant_casts = true + +[[tool.mypy.overrides]] +module = "iteraconnect.config" +disallow_untyped_defs = true +disallow_any_generics = true +warn_return_any = true + +[tool.importlinter] +root_package = "iteraconnect" + +[[tool.importlinter.contracts]] +name = "Runtime dependencies point from entry points toward configuration" +type = "layers" +containers = ["iteraconnect"] +exhaustive = true +layers = [ + "__main__", + "cli", + "app", + "smoke", + "diagnostics | gateway | integrations | launch | native", + "network | settings", + "config", +] diff --git a/requirements-dev.txt b/requirements-dev.txt index 5264a85..2647187 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -1,2 +1,4 @@ ruff==0.17.5 build==1.6.1 +mypy==2.4.1 +import-linter==2.16 diff --git a/scripts/verify.py b/scripts/verify.py new file mode 100644 index 0000000..a9a0186 --- /dev/null +++ b/scripts/verify.py @@ -0,0 +1,89 @@ +"""Check the checkout and exercise the distributions built from it.""" + +import argparse +import hashlib +import json +import os +import shutil +import subprocess +import sys +import sysconfig +import tempfile +import venv +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +# tlaplus/tlaplus release v1.7.4, tla2tools.jar (TLC 2.19). +TLC_SHA256 = "936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88" + + +def check_wheel(wheel: Path, work: Path) -> None: + environment = work / "env" + venv.EnvBuilder(with_pip=True).create(environment) + scripts = environment / ("Scripts" if os.name == "nt" else "bin") + python = scripts / ("python.exe" if os.name == "nt" else "python") + cli = scripts / ("itera-connect.exe" if os.name == "nt" else "itera-connect") + subprocess.run( + [python, "-I", "-m", "pip", "--isolated", "install", "--no-index", "--no-deps", wheel], + cwd=work, + check=True, + ) + # Give the installed CLI and fixture suite a disposable home and state directory. + env = {k: os.environ[k] for k in ("PATH", "SystemRoot", "TEMP", "TMP") if k in os.environ} + env.update(HOME=str(work), USERPROFILE=str(work), ITERACONNECT_HOME=str(work / "state")) + subprocess.run([cli, "init"], cwd=work, env=env, check=True) + result = subprocess.run( + [cli, "provider", "list"], cwd=work, env=env, check=True, capture_output=True + ) + if json.loads(result.stdout)["active_provider"] != "iteracompute": + raise SystemExit("Installed CLI failed to load the initialized profile") + subprocess.run( + [python, "-I", "-m", "unittest", "discover", "-v", "-s", ROOT / "tests", "-t", ROOT], + cwd=work, + env=env, + check=True, + ) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--dist-dir", type=Path, help="new directory for the verified artifacts") + parser.add_argument("--tlc-jar", type=Path, help="also check the native journal model with TLC") + args = parser.parse_args() + python = sys.executable + lint_imports = Path(sysconfig.get_path("scripts")) / ( + "lint-imports.exe" if os.name == "nt" else "lint-imports" + ) + for command in ( + [python, "-m", "ruff", "check", "."], + [python, "-m", "ruff", "format", "--check", "."], + [python, "-m", "mypy"], + [lint_imports], + ): + subprocess.run(command, cwd=ROOT, check=True) + with tempfile.TemporaryDirectory() as temporary: + work = Path(temporary) + if args.tlc_jar: + jar = args.tlc_jar.resolve() + with jar.open("rb") as file: + if hashlib.file_digest(file, "sha256").hexdigest() != TLC_SHA256: + raise SystemExit("Unexpected digest for the TLC release jar") + subprocess.run( + ["java", "-cp", jar, "tlc2.TLC", "-metadir", work / "tlc", "NativeJournal"], + cwd=ROOT / "verification", + check=True, + ) + dist = work / "dist" + subprocess.run([python, "-m", "build", "--outdir", dist], cwd=ROOT, check=True) + # The default build makes an sdist and builds its wheel from that sdist. + (wheel,) = dist.glob("*.whl") + (sdist,) = dist.glob("*.tar.gz") + check_wheel(wheel, work) + if args.dist_dir: + args.dist_dir.mkdir(parents=True, exist_ok=False) + for artifact in (sdist, wheel): + shutil.copy2(artifact, args.dist_dir) + + +if __name__ == "__main__": + main() diff --git a/src/iteraconnect/config.py b/src/iteraconnect/config.py index f122afa..742f4fb 100644 --- a/src/iteraconnect/config.py +++ b/src/iteraconnect/config.py @@ -10,10 +10,34 @@ import secrets import tempfile from pathlib import Path +from typing import NotRequired, TypedDict from urllib.parse import urlsplit PROTOCOLS = ("chat", "responses", "anthropic", "gemini") -DEFAULT = { + + +class ProviderConfig(TypedDict): + name: str + key_env: str + default_model: str + endpoints: dict[str, str] + allow_http: NotRequired[bool] + + +class GatewayConfig(TypedDict): + host: str + port: int + timeout: float + + +class RuntimeConfig(TypedDict): + schema_version: int + active_provider: str + gateway: GatewayConfig + providers: dict[str, ProviderConfig] + + +DEFAULT: RuntimeConfig = { "schema_version": 1, "active_provider": "iteracompute", "gateway": {"host": "127.0.0.1", "port": 18423, "timeout": 180}, @@ -81,7 +105,7 @@ def validate_url(value: str, allow_http: bool = False) -> str: return value.rstrip("/") -def validate(data: dict) -> dict: +def validate(data: RuntimeConfig) -> RuntimeConfig: try: if data["schema_version"] != 1 or not data["providers"]: raise ValueError @@ -122,7 +146,7 @@ def validate(data: dict) -> dict: return data -def load(path: Path | None = None) -> dict: +def load(path: Path | None = None) -> RuntimeConfig: path = path or state_dir() / "config.json" if not path.exists(): return copy.deepcopy(DEFAULT) @@ -132,7 +156,7 @@ def load(path: Path | None = None) -> dict: raise ConnectError("Invalid configuration JSON") from None -def save(data: dict, path: Path | None = None) -> None: +def save(data: RuntimeConfig, path: Path | None = None) -> None: private_write(path or state_dir() / "config.json", json.dumps(validate(data), indent=2) + "\n") @@ -152,7 +176,7 @@ def gateway_key() -> str: if len(value) < 24: raise ConnectError( "Invalid gateway.key; restore it or remove it to create a new local key" - ) + ) from None return value value = "ic-" + secrets.token_urlsafe(32) with os.fdopen(fd, "w") as f: @@ -160,7 +184,7 @@ def gateway_key() -> str: return value -def api_key(provider: dict, required: bool = True) -> str: +def api_key(provider: ProviderConfig, required: bool = True) -> str: value = os.environ.get(provider["key_env"], "") if required and not value: raise ConnectError(f"Set {provider['key_env']} in the gateway process environment") @@ -169,6 +193,6 @@ def api_key(provider: dict, required: bool = True) -> str: return value -def gateway_url(config: dict, pid: str | None = None) -> str: +def gateway_url(config: RuntimeConfig, pid: str | None = None) -> str: base = f"http://127.0.0.1:{config['gateway']['port']}" return base + (f"/p/{pid}" if pid else "") diff --git a/src/iteraconnect/gateway.py b/src/iteraconnect/gateway.py index 2b328aa..99ff1b7 100644 --- a/src/iteraconnect/gateway.py +++ b/src/iteraconnect/gateway.py @@ -11,7 +11,7 @@ from urllib.parse import parse_qsl, unquote, urlsplit from . import __version__ -from .config import ConnectError, api_key, gateway_key +from .config import ConnectError, ProviderConfig, RuntimeConfig, api_key, gateway_key from .network import MAX_JSON, json_request, request # Explicit inference routes keep provider administration APIs unreachable. @@ -26,7 +26,7 @@ } -def provider_models(provider: dict, timeout=20) -> list[dict]: +def provider_models(provider: ProviderConfig, timeout=20) -> list[dict]: endpoints = provider["endpoints"] if base := endpoints.get("chat") or endpoints.get("responses"): url = base + "/models" @@ -48,7 +48,7 @@ class Gateway(ThreadingHTTPServer): daemon_threads = True block_on_close = False - def __init__(self, config: dict, key: str | None = None, address=None): + def __init__(self, config: RuntimeConfig, key: str | None = None, address=None): self.config = config self.key = key or gateway_key() self.slots = threading.BoundedSemaphore(64) @@ -183,11 +183,10 @@ def do_POST(self): def relay(self): pid, path = self.split_route() - route = ROUTES.get(path) gemini = re.fullmatch( r"/v1beta/models/([^:]+):(generateContent|streamGenerateContent)", path ) - if not route and not gemini: + if path not in ROUTES and not gemini: self.fail(404, "Inference route not found") return if self.headers.get("Transfer-Encoding"): @@ -220,7 +219,7 @@ def relay(self): pid, model = prefix, rest pid = pid or self.server.config["active_provider"] provider = providers[pid] - protocol, suffix = ("gemini", f"/models/{model}:{gemini[2]}") if gemini else route + protocol, suffix = ("gemini", f"/models/{model}:{gemini[2]}") if gemini else ROUTES[path] suffix += self.inference_query if protocol not in provider["endpoints"]: self.fail( diff --git a/src/iteraconnect/integrations.py b/src/iteraconnect/integrations.py index 4b06d9d..fe663b4 100644 --- a/src/iteraconnect/integrations.py +++ b/src/iteraconnect/integrations.py @@ -13,7 +13,7 @@ from pathlib import Path from urllib.parse import urlencode -from .config import ConnectError, gateway_key, gateway_url, private_write, state_dir +from .config import ConnectError, RuntimeConfig, gateway_key, gateway_url, private_write, state_dir from .network import json_request CC_FORMATS = { @@ -126,7 +126,7 @@ def magpie_providers() -> dict: ) from None -def sync_magpie(config: dict) -> list[str]: +def sync_magpie(config: RuntimeConfig) -> list[str]: base = gateway_url(config) hello = json_request("GET", base + "/health", timeout=3) if hello.get("name") != "iteraconnect": @@ -169,7 +169,7 @@ def sync_magpie(config: dict) -> list[str]: return synced -def connect(config: dict, target: str, pid: str, model: str | None = None): +def connect(config: RuntimeConfig, target: str, pid: str, model: str | None = None): vendor_env_names = [p["key_env"] for p in config["providers"].values()] # WorkBuddy selects a model per task; its adapter connects a provider/picker, not a default model. if target in ("workbuddy", "workbuddy-ai"): @@ -183,7 +183,9 @@ def connect(config: dict, target: str, pid: str, model: str | None = None): ) -def cc_link(config: dict, target: str, pid: str, model=None, api_format=None, via="gateway") -> str: +def cc_link( + config: RuntimeConfig, target: str, pid: str, model=None, api_format=None, via="gateway" +) -> str: if target not in CC_FORMATS: raise ConnectError("This client has no CC Switch provider import; use: connect ") fmt = api_format or CC_FORMATS[target] @@ -226,7 +228,7 @@ def cc_link(config: dict, target: str, pid: str, model=None, api_format=None, vi ) -def export_fragment(config: dict, target: str, pid: str, model=None) -> str: +def export_fragment(config: RuntimeConfig, target: str, pid: str, model=None) -> str: """Standalone fragments for manual merging; never overwrite native config files.""" root, key = gateway_url(config, pid), gateway_key() p = config["providers"][pid] @@ -240,6 +242,7 @@ def export_fragment(config: dict, target: str, pid: str, model=None) -> str: f'base_url = {json.dumps(root + "/v1")}\nenv_key = "ITERACONNECT_GATEWAY_KEY"\n' 'wire_api = "responses"\nrequires_openai_auth = false\nsupports_websockets = false\n' ) + value: dict[str, object] | list[dict[str, object]] if target == "claude": if "anthropic" not in p["endpoints"]: raise ConnectError("Claude Code needs Messages; connect through Magpie for translation") diff --git a/src/iteraconnect/launch.py b/src/iteraconnect/launch.py index 191aefc..f05ddd6 100644 --- a/src/iteraconnect/launch.py +++ b/src/iteraconnect/launch.py @@ -7,10 +7,10 @@ import shutil import subprocess -from .config import ConnectError, api_key, gateway_key, gateway_url +from .config import ConnectError, RuntimeConfig, api_key, gateway_key, gateway_url -def launch_args(config: dict, target: str, pid: str, model=None, via="gateway", args=()): +def launch_args(config: RuntimeConfig, target: str, pid: str, model=None, via="gateway", args=()): p = config["providers"][pid] selected = model or p["default_model"] protocol = {"claude": "anthropic", "codex": "responses"}.get(target) diff --git a/src/iteraconnect/native.py b/src/iteraconnect/native.py index 691ebc2..4961da5 100644 --- a/src/iteraconnect/native.py +++ b/src/iteraconnect/native.py @@ -173,7 +173,7 @@ def render_native(target, text, config, pid, model): return edit_codex(text, root, key, model) if target == "hermes": # Stale explicit model routes and key commands can override a newly selected named provider. - removals = [ + removals: list[tuple[str, ...]] = [ ("model", key) for key in ("base_url", "api", "api_key", "api_mode", "key_env", "api_key_env") ] @@ -209,14 +209,14 @@ def render_native(target, text, config, pid, model): raise ConnectError("Hermes YAML 包含文档指令,请使用手动导出。") for path in removals: text = yaml_put(text, path, None, remove=True) - for path, value in ( - (["model", "provider"], "custom:iteraconnect"), - (["model", "default"], model), - (["providers", "iteraconnect", "base_url"], root + "/v1"), - (["providers", "iteraconnect", "api_key"], key), - (["providers", "iteraconnect", "transport"], "chat_completions"), + for path, setting in ( + (("model", "provider"), "custom:iteraconnect"), + (("model", "default"), model), + (("providers", "iteraconnect", "base_url"), root + "/v1"), + (("providers", "iteraconnect", "api_key"), key), + (("providers", "iteraconnect", "transport"), "chat_completions"), ): - text = yaml_put(text, path, value) + text = yaml_put(text, path, setting) return text try: value = ( @@ -243,6 +243,8 @@ def render_native(target, text, config, pid, model): value["models"] = models else: value = models + elif not isinstance(value, dict): + raise ValueError elif target == "claude": # Explicitly neutralize competing API-key and cloud-provider settings at this scope. merge_dict( diff --git a/src/iteraconnect/network.py b/src/iteraconnect/network.py index a98844a..6ae97f3 100644 --- a/src/iteraconnect/network.py +++ b/src/iteraconnect/network.py @@ -12,13 +12,19 @@ MAX_JSON = 16 * 1024 * 1024 -def request(method: str, url: str, headers: dict, body: bytes | None = None, timeout=180): +def request( + method: str, url: str, headers: dict[str, str], body: bytes | None = None, timeout: float = 180 +) -> tuple[http.client.HTTPConnection, http.client.HTTPResponse]: p = urlsplit(url) - cls = http.client.HTTPSConnection if p.scheme == "https" else http.client.HTTPConnection - options = {"timeout": timeout} + if not p.hostname: + raise ConnectError("Upstream URL requires a host") + conn: http.client.HTTPConnection if p.scheme == "https": - options["context"] = ssl.create_default_context() - conn = cls(p.hostname, p.port, **options) + conn = http.client.HTTPSConnection( + p.hostname, p.port, timeout=timeout, context=ssl.create_default_context() + ) + else: + conn = http.client.HTTPConnection(p.hostname, p.port, timeout=timeout) path = p.path or "/" if p.query: path += "?" + p.query diff --git a/src/iteraconnect/settings.py b/src/iteraconnect/settings.py index 61621a0..edc964a 100644 --- a/src/iteraconnect/settings.py +++ b/src/iteraconnect/settings.py @@ -9,7 +9,7 @@ import tomllib from pathlib import Path -from .config import DEFAULT, ConnectError, private_write, validate, validate_url +from .config import DEFAULT, ConnectError, RuntimeConfig, private_write, validate, validate_url CLIENTS = { "claude": ("Claude Code", "anthropic"), @@ -97,7 +97,7 @@ def read_settings(path: Path): raise ConnectError("无法读取本地 TOML 配置,请检查引号;错误内容不会显示密钥。") from None -def runtime_config(data, port=18423): +def runtime_config(data, port: int = 18423) -> RuntimeConfig: """The app exclusively uses this private file, never an unrelated inherited vendor key.""" config = copy.deepcopy(DEFAULT) config["active_provider"] = data["selected_provider"] diff --git a/tests/test_app.py b/tests/test_app.py index 205f57b..ebbfc17 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -122,6 +122,41 @@ def test_all_adapters_preserve_settings_reconnect_and_restore_exactly(self): disconnect_native(target, home, home / "backups") self.assertEqual(path.read_text(), original) + def test_restore_after_journal_write_but_before_config_replacement(self): + from iteraconnect.config import private_write + + for original in (None, b'{"theme":"dark"}\r\n'): + for reconnect in (False, True): + with ( + self.subTest(existing=original is not None, reconnect=reconnect), + tempfile.TemporaryDirectory() as directory, + ): + home = Path(directory) + backups = home / "backups" + path = client_path("claude", home).resolve() + if original is not None: + private_write(path, original) + if reconnect: + connect_native("claude", DEFAULT, "iteracompute", MODEL, home, backups) + + def interrupt_config_write(destination, content, config_path=path): + if destination == config_path: + raise OSError("simulated interruption") + private_write(destination, content) + + with ( + patch( + "iteraconnect.native.private_write", side_effect=interrupt_config_write + ), + self.assertRaises(OSError), + ): + connect_native( + "claude", DEFAULT, "iteracompute", MODEL + "-new", home, backups + ) + disconnect_native("claude", home, backups) + self.assertEqual(path.read_bytes() if path.exists() else None, original) + self.assertFalse((backups / "claude.json").exists()) + def test_restoring_a_new_file_removes_it_and_later_edits_are_protected(self): with tempfile.TemporaryDirectory() as directory: home = Path(directory) diff --git a/tests/test_distribution.py b/tests/test_distribution.py new file mode 100644 index 0000000..2e9e3d4 --- /dev/null +++ b/tests/test_distribution.py @@ -0,0 +1,39 @@ +"""Contracts for the installed Python distribution and its dependency-free runtime.""" + +import ast +import json +import sys +import unittest +from importlib.metadata import distribution +from pathlib import Path + +import iteraconnect + + +class DistributionTests(unittest.TestCase): + def test_metadata_and_upstream_resources(self): + package = distribution("iteracompute-agent-connect") + self.assertEqual(package.version, iteraconnect.__version__) + self.assertFalse(package.requires) + root = Path(iteraconnect.__file__).parent + pins = json.loads((root / "upstreams.lock.json").read_bytes()) + self.assertTrue(pins["magpie"]["assets"]) + notices = (root / "upstream-notices.txt").read_text(encoding="utf-8") + self.assertIn("MIT License", notices) + self.assertTrue(package.read_text("licenses/LICENSE")) + self.assertEqual(package.read_text("licenses/THIRD_PARTY_NOTICES"), notices) + + def test_runtime_imports_only_stdlib_and_its_own_package(self): + root = Path(iteraconnect.__file__).parent + allowed = sys.stdlib_module_names | {"iteraconnect"} + for path in root.rglob("*.py"): + for node in ast.walk(ast.parse(path.read_bytes())): + if isinstance(node, ast.Import): + names = [alias.name for alias in node.names] + elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module: + names = [node.module] + else: + continue + for name in names: + with self.subTest(module=path.relative_to(root), line=node.lineno, name=name): + self.assertIn(name.partition(".")[0], allowed) diff --git a/tests/test_magpie.py b/tests/test_magpie.py index 49789ae..667dc2c 100644 --- a/tests/test_magpie.py +++ b/tests/test_magpie.py @@ -82,7 +82,7 @@ def setUpClass(cls): break except Exception: if cls.process.poll() is not None: - raise AssertionError("Magpie failed to start in sandbox") + raise AssertionError("Magpie failed to start in sandbox") from None time.sleep(0.1) else: raise AssertionError("Magpie did not become ready") diff --git a/verification/NativeJournal.cfg b/verification/NativeJournal.cfg new file mode 100644 index 0000000..4afe7e1 --- /dev/null +++ b/verification/NativeJournal.cfg @@ -0,0 +1,3 @@ +SPECIFICATION Spec +INVARIANT OriginalPreserved Recoverable +PROPERTY ProtectExternalEdit diff --git a/verification/NativeJournal.tla b/verification/NativeJournal.tla new file mode 100644 index 0000000..14bac3a --- /dev/null +++ b/verification/NativeJournal.tla @@ -0,0 +1,53 @@ +-------------------------- MODULE NativeJournal -------------------------- +\* One client path, serialized connect/restore operations and atomic file writes. +\* Each string denotes a distinct file image. "absent" denotes no original file. +VARIABLES original, disk, journal, pending +vars == <> +Images == {"modelA", "modelB"} +NoJournal == [saved |-> "none", previous |-> "none", applied |-> "none"] + +Init == + /\ original \in {"existing", "absent"} + /\ disk = original + /\ journal = NoJournal + /\ pending = FALSE + +Prepare(image) == + /\ ~pending + /\ IF journal = NoJournal THEN TRUE ELSE disk = journal.applied + /\ journal' = [saved |-> IF journal = NoJournal THEN disk ELSE journal.saved, + previous |-> disk, applied |-> image] + /\ pending' = TRUE + /\ UNCHANGED <> + +FinishWrite == + /\ pending + /\ disk' = journal.applied + /\ pending' = FALSE + /\ UNCHANGED <> + +InterruptWrite == + /\ pending + /\ pending' = FALSE + /\ UNCHANGED <> + +EditBetweenOperations == + /\ ~pending /\ journal # NoJournal + /\ disk' = "external edit" + /\ UNCHANGED <> + +Restore == + /\ ~pending /\ journal # NoJournal + /\ disk \in {journal.applied, journal.previous} + /\ disk' = journal.saved + /\ journal' = NoJournal + /\ UNCHANGED <> + +Next == (\E image \in Images : Prepare(image)) + \/ FinishWrite \/ InterruptWrite \/ EditBetweenOperations \/ Restore +Spec == Init /\ [][Next]_vars + +OriginalPreserved == IF journal = NoJournal THEN disk = original ELSE journal.saved = original +Recoverable == (~pending /\ journal # NoJournal /\ disk # "external edit") => ENABLED Restore +ProtectExternalEdit == [][disk = "external edit" => UNCHANGED <>]_vars +=============================================================================