From 509424c1510c2b1b5acc125d8fb171bd048687f9 Mon Sep 17 00:00:00 2001 From: codeasier Date: Sat, 3 Oct 2026 21:18:00 +0800 Subject: [PATCH] fix(skills): verify CLI environment prefix during setup --- docs/en/skills.md | 12 +++ docs/zh/skills.md | 10 +++ skills/pt-snap-setup/SKILL.md | 46 ++++++++-- .../bundled_skills/pt-snap-setup/SKILL.md | 46 ++++++++-- tests/skills/test_setup_contract.py | 83 ++++++++++++++++++- 5 files changed, 178 insertions(+), 19 deletions(-) diff --git a/docs/en/skills.md b/docs/en/skills.md index 85e4839..a4a0bb5 100644 --- a/docs/en/skills.md +++ b/docs/en/skills.md @@ -114,3 +114,15 @@ After an install, upgrade, or uninstall that changes skill files, restart the ag | `pt-snap-memory-fragmentation` | Diagnosing allocator gaps and reserved-pool pressure | Skill management is CLI-only. + +### Setup readiness + +`pt-snap-setup` reports `ready` only after CLI help succeeds and the selected +Python and CLI shebang interpreter match on both normalized `sys.executable` +and `sys.prefix`. Matching executable realpaths alone is insufficient: different +venvs can share a base interpreter. Both probes preserve the original execution +paths; normalization is only for comparison, so directory symlink aliases of the +same environment still match. Simple `env ` shebangs use the current `PATH`. +Unresolved shebangs, unsupported argument/wrapper semantics (including `env -S`), +or failed identity probes leave `CLI ownership unverified`. A mismatch reports +`CLI belongs to another Python environment`; installation still requires confirmation. diff --git a/docs/zh/skills.md b/docs/zh/skills.md index 92acc59..ba7dc5b 100644 --- a/docs/zh/skills.md +++ b/docs/zh/skills.md @@ -110,3 +110,13 @@ pt-snap skill uninstall --project --target cursor | `pt-snap-memory-fragmentation` | 诊断分配器空洞和 reserved 池压力 | Skill 管理只通过 CLI 提供。 + +### Setup 就绪判据 + +`pt-snap-setup` 只有在 CLI 帮助执行成功,且所选 Python 与 CLI shebang 解释器的 +`sys.executable` 和 `sys.prefix` 规范化后都相同时,才报告 `ready`。 +仅比较可执行文件的 realpath 不够:不同 venv 可以共享同一基础解释器。 +两侧探测均保留原始执行路径,规范化只用于比较,因此同一环境的目录符号链接别名仍能匹配。 +简单的 `env ` shebang 按当前 `PATH` 解析;无法解析的 shebang、不支持的参数或 +包装器语义(包括 `env -S`),以及身份探测失败,均保留为 `CLI ownership unverified`。 +身份不匹配则报告 `CLI belongs to another Python environment`;安装仍需用户确认。 diff --git a/skills/pt-snap-setup/SKILL.md b/skills/pt-snap-setup/SKILL.md index e2866dc..8d5263f 100644 --- a/skills/pt-snap-setup/SKILL.md +++ b/skills/pt-snap-setup/SKILL.md @@ -57,9 +57,36 @@ If both commands succeed, save the first command's output as `" -c "from pathlib import Path; import sys; print(Path(sys.argv[1]).open(encoding='utf-8').readline().strip())" "" ``` -Resolve the shebang interpreter and compare `realpath` values computed temporarily for the shebang interpreter and ``. For an `/usr/bin/env ` shebang, resolve `` in the current `PATH` before comparing. Never replace `` with its `realpath`; canonicalization is only for this ownership comparison. Report `ready` only when `pt-snap --help` succeeds and both comparison paths identify the same interpreter. +Resolve a plain absolute-path shebang as ``, preserving its original path. For a simple `/usr/bin/env ` shebang, resolve `` in the current `PATH` without dereferencing symlinks. If the shebang is missing, cannot be resolved, or uses arguments/wrappers whose semantics cannot be preserved (including `env -S`), report `CLI ownership unverified`; do not drop arguments and probe a different invocation. -If the shebang is missing or cannot be resolved, report `CLI ownership unverified`. If it points to another interpreter, report `CLI belongs to another Python environment`. Do not report the selected Python environment as ready and do not reinstall automatically. +Never replace `` with its `realpath`; preserve `` too. Two different venvs, or a venv and its base environment, may share the same executable `realpath`. Probe both environments through their original execution paths, then compare **both** normalized `sys.executable` and normalized `sys.prefix`. Normalize with `normcase(realpath(...))` only for comparison: directory symlink aliases of the same environment may have different raw prefixes. + +For a resolved interpreter without shebang arguments, run this read-only ownership probe: +```bash +"" - "" <<'PY' +import json +import os +import subprocess +import sys + +selected = {"executable": sys.executable, "prefix": sys.prefix} +probe = "import json, sys; print(json.dumps({'executable': sys.executable, 'prefix': sys.prefix}))" +try: + cli = json.loads(subprocess.check_output( + [sys.argv[1], "-c", probe], text=True, timeout=10, + )) + def identity(info): + return tuple(os.path.normcase(os.path.realpath(info[key])) + for key in ("executable", "prefix")) + matches = identity(selected) == identity(cli) +except (OSError, subprocess.SubprocessError, ValueError, KeyError, TypeError) as error: + print(f"CLI ownership unverified: {error}") +else: + print(json.dumps({"selected": selected, "cli": cli})) + print("matches selected Python" if matches else "CLI belongs to another Python environment") +PY +``` +Report `ready` only when `pt-snap --help` succeeds and the probe reports `matches selected Python`. A failed identity probe leaves ownership unverified. If either normalized identity component differs, report `CLI belongs to another Python environment`. Do not report the selected Python environment as ready and do not reinstall automatically. ### 3. If the CLI is unavailable or belongs elsewhere, check package availability Run this check if `pt-snap --help` failed or Step 2 did not verify ownership: @@ -110,11 +137,11 @@ pt-snap --help "" -c "import pt_snap_cli; print(pt_snap_cli.__file__)" "" -m pip show pt-snap-cli ``` -Repeat the shebang comparison from Step 2 when `command -v pt-snap` and `pt-snap --help` succeed. Then report the final state using the result categories in the output template. +Repeat the shebang resolution and environment identity probe from Step 2 when `command -v pt-snap` and `pt-snap --help` succeed. Then report the final state using the result categories in the output template. If installation succeeds but `pt-snap --help` still fails while the import succeeds, report `CLI missing but import works` and explain that the executable directory is not on the current shell `PATH`. Do not run another install automatically. -If `pt-snap` still resolves to another interpreter, report `CLI belongs to another Python environment`, even when the selected Python can import the package. Do not report `ready` until CLI ownership matches. +If `pt-snap` still resolves to another environment, report `CLI belongs to another Python environment`, even when the selected Python can import the package. Do not report `ready` until CLI ownership matches. ### 7. Stop if verification still fails If verification still fails after the confirmed install command, stop and report the exact failure. Do not guess another environment, do not try a different interpreter automatically, and do not keep running more install commands without user confirmation. @@ -130,7 +157,8 @@ Report results in this structure: - Detected availability: - `command -v pt-snap`: `` - `pt-snap --help`: `` - - CLI shebang interpreter: `` + - CLI shebang interpreter: `` + - Selected/CLI identity probes: `` - CLI ownership: `` - ` -c "import pt_snap_cli; print(pt_snap_cli.__file__)"`: `` - ` -m pip show pt-snap-cli`: `` @@ -142,9 +170,9 @@ Report results in this structure: - `` Use these categories consistently before and after installation: -- `ready`: CLI help succeeds and the CLI shebang resolves to the selected Python. -- `CLI belongs to another Python environment`: CLI help succeeds, but its shebang resolves to a different interpreter. -- `CLI ownership unverified`: CLI help succeeds, but its shebang is missing or cannot be resolved. +- `ready`: CLI help succeeds and both identity probes match on normalized `sys.executable` and `sys.prefix`. +- `CLI belongs to another Python environment`: CLI help succeeds, but the identity probes differ on either normalized `sys.executable` or `sys.prefix`. +- `CLI ownership unverified`: CLI help succeeds, but its shebang cannot be resolved with its invocation semantics preserved, or an identity probe fails. - `CLI missing but import works`: the selected Python imports the package, but no matching CLI is available. - `not installed`: neither a matching CLI nor a package import is available and no install was attempted. - `installation declined`: installation was offered and the user declined it. @@ -164,7 +192,7 @@ Use these categories consistently before and after installation: - `python` or `python3` selected once and its uncanonicalized `sys.executable` path used consistently. - Active Python environment identified with ` -V`, ` -m pip --version`, and `sys.executable`. - `command -v pt-snap` and `pt-snap --help` checked in the current shell. -- Resolved CLI shebang interpreter compared with the selected Python before reporting `ready`. +- Both interpreters probed through preserved execution paths; normalized `sys.executable` and `sys.prefix` compared before reporting `ready`. - Package import checked if the CLI is unavailable or its ownership is not verified. - ` -m pip show pt-snap-cli` checked when the package import succeeds but the CLI is unavailable or belongs elsewhere. - User confirmation obtained before any ` -m pip install ...` command. diff --git a/src/pt_snap_cli/bundled_skills/pt-snap-setup/SKILL.md b/src/pt_snap_cli/bundled_skills/pt-snap-setup/SKILL.md index e2866dc..8d5263f 100644 --- a/src/pt_snap_cli/bundled_skills/pt-snap-setup/SKILL.md +++ b/src/pt_snap_cli/bundled_skills/pt-snap-setup/SKILL.md @@ -57,9 +57,36 @@ If both commands succeed, save the first command's output as `" -c "from pathlib import Path; import sys; print(Path(sys.argv[1]).open(encoding='utf-8').readline().strip())" "" ``` -Resolve the shebang interpreter and compare `realpath` values computed temporarily for the shebang interpreter and ``. For an `/usr/bin/env ` shebang, resolve `` in the current `PATH` before comparing. Never replace `` with its `realpath`; canonicalization is only for this ownership comparison. Report `ready` only when `pt-snap --help` succeeds and both comparison paths identify the same interpreter. +Resolve a plain absolute-path shebang as ``, preserving its original path. For a simple `/usr/bin/env ` shebang, resolve `` in the current `PATH` without dereferencing symlinks. If the shebang is missing, cannot be resolved, or uses arguments/wrappers whose semantics cannot be preserved (including `env -S`), report `CLI ownership unverified`; do not drop arguments and probe a different invocation. -If the shebang is missing or cannot be resolved, report `CLI ownership unverified`. If it points to another interpreter, report `CLI belongs to another Python environment`. Do not report the selected Python environment as ready and do not reinstall automatically. +Never replace `` with its `realpath`; preserve `` too. Two different venvs, or a venv and its base environment, may share the same executable `realpath`. Probe both environments through their original execution paths, then compare **both** normalized `sys.executable` and normalized `sys.prefix`. Normalize with `normcase(realpath(...))` only for comparison: directory symlink aliases of the same environment may have different raw prefixes. + +For a resolved interpreter without shebang arguments, run this read-only ownership probe: +```bash +"" - "" <<'PY' +import json +import os +import subprocess +import sys + +selected = {"executable": sys.executable, "prefix": sys.prefix} +probe = "import json, sys; print(json.dumps({'executable': sys.executable, 'prefix': sys.prefix}))" +try: + cli = json.loads(subprocess.check_output( + [sys.argv[1], "-c", probe], text=True, timeout=10, + )) + def identity(info): + return tuple(os.path.normcase(os.path.realpath(info[key])) + for key in ("executable", "prefix")) + matches = identity(selected) == identity(cli) +except (OSError, subprocess.SubprocessError, ValueError, KeyError, TypeError) as error: + print(f"CLI ownership unverified: {error}") +else: + print(json.dumps({"selected": selected, "cli": cli})) + print("matches selected Python" if matches else "CLI belongs to another Python environment") +PY +``` +Report `ready` only when `pt-snap --help` succeeds and the probe reports `matches selected Python`. A failed identity probe leaves ownership unverified. If either normalized identity component differs, report `CLI belongs to another Python environment`. Do not report the selected Python environment as ready and do not reinstall automatically. ### 3. If the CLI is unavailable or belongs elsewhere, check package availability Run this check if `pt-snap --help` failed or Step 2 did not verify ownership: @@ -110,11 +137,11 @@ pt-snap --help "" -c "import pt_snap_cli; print(pt_snap_cli.__file__)" "" -m pip show pt-snap-cli ``` -Repeat the shebang comparison from Step 2 when `command -v pt-snap` and `pt-snap --help` succeed. Then report the final state using the result categories in the output template. +Repeat the shebang resolution and environment identity probe from Step 2 when `command -v pt-snap` and `pt-snap --help` succeed. Then report the final state using the result categories in the output template. If installation succeeds but `pt-snap --help` still fails while the import succeeds, report `CLI missing but import works` and explain that the executable directory is not on the current shell `PATH`. Do not run another install automatically. -If `pt-snap` still resolves to another interpreter, report `CLI belongs to another Python environment`, even when the selected Python can import the package. Do not report `ready` until CLI ownership matches. +If `pt-snap` still resolves to another environment, report `CLI belongs to another Python environment`, even when the selected Python can import the package. Do not report `ready` until CLI ownership matches. ### 7. Stop if verification still fails If verification still fails after the confirmed install command, stop and report the exact failure. Do not guess another environment, do not try a different interpreter automatically, and do not keep running more install commands without user confirmation. @@ -130,7 +157,8 @@ Report results in this structure: - Detected availability: - `command -v pt-snap`: `` - `pt-snap --help`: `` - - CLI shebang interpreter: `` + - CLI shebang interpreter: `` + - Selected/CLI identity probes: `` - CLI ownership: `` - ` -c "import pt_snap_cli; print(pt_snap_cli.__file__)"`: `` - ` -m pip show pt-snap-cli`: `` @@ -142,9 +170,9 @@ Report results in this structure: - `` Use these categories consistently before and after installation: -- `ready`: CLI help succeeds and the CLI shebang resolves to the selected Python. -- `CLI belongs to another Python environment`: CLI help succeeds, but its shebang resolves to a different interpreter. -- `CLI ownership unverified`: CLI help succeeds, but its shebang is missing or cannot be resolved. +- `ready`: CLI help succeeds and both identity probes match on normalized `sys.executable` and `sys.prefix`. +- `CLI belongs to another Python environment`: CLI help succeeds, but the identity probes differ on either normalized `sys.executable` or `sys.prefix`. +- `CLI ownership unverified`: CLI help succeeds, but its shebang cannot be resolved with its invocation semantics preserved, or an identity probe fails. - `CLI missing but import works`: the selected Python imports the package, but no matching CLI is available. - `not installed`: neither a matching CLI nor a package import is available and no install was attempted. - `installation declined`: installation was offered and the user declined it. @@ -164,7 +192,7 @@ Use these categories consistently before and after installation: - `python` or `python3` selected once and its uncanonicalized `sys.executable` path used consistently. - Active Python environment identified with ` -V`, ` -m pip --version`, and `sys.executable`. - `command -v pt-snap` and `pt-snap --help` checked in the current shell. -- Resolved CLI shebang interpreter compared with the selected Python before reporting `ready`. +- Both interpreters probed through preserved execution paths; normalized `sys.executable` and `sys.prefix` compared before reporting `ready`. - Package import checked if the CLI is unavailable or its ownership is not verified. - ` -m pip show pt-snap-cli` checked when the package import succeeds but the CLI is unavailable or belongs elsewhere. - User confirmation obtained before any ` -m pip install ...` command. diff --git a/tests/skills/test_setup_contract.py b/tests/skills/test_setup_contract.py index 80524a7..f74b033 100644 --- a/tests/skills/test_setup_contract.py +++ b/tests/skills/test_setup_contract.py @@ -1,7 +1,9 @@ from __future__ import annotations +import json import os import subprocess +import sys import venv from pathlib import Path @@ -13,7 +15,7 @@ @pytest.mark.skipif(os.name == "nt", reason="POSIX venvs use interpreter symlinks") def test_setup_skill_preserves_virtual_environment_interpreter_path(tmp_path: Path) -> None: environment = tmp_path / "venv" - venv.EnvBuilder(with_pip=True, symlinks=True).create(environment) + venv.EnvBuilder(with_pip=False, symlinks=True).create(environment) candidate = environment / "bin" / "python" child_env = os.environ.copy() child_env.pop("__PYVENV_LAUNCHER__", None) @@ -46,3 +48,82 @@ def test_setup_skill_preserves_virtual_environment_interpreter_path(tmp_path: Pa skill = SKILL_PATH.read_text() assert '"" -c "import sys; print(sys.executable)"' in skill assert "Never replace `` with its `realpath`" in skill + + +def _run_ownership_probe(selected: Path, cli: Path) -> list[str]: + """Execute the shipped probe, not a test-only copy of its decision rule.""" + skill = SKILL_PATH.read_text() + probe = skill.split("<<'PY'\n", 1)[1].split("\nPY\n", 1)[0] + child_env = os.environ.copy() + child_env.pop("__PYVENV_LAUNCHER__", None) + return subprocess.run( + [selected, "-", cli], + input=probe, + check=True, + capture_output=True, + env=child_env, + text=True, + timeout=20, + ).stdout.splitlines() + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX venvs use interpreter symlinks") +@pytest.mark.parametrize( + ("selected_name", "cli_name", "matches"), + [ + ("first", "first", True), + ("first", "second", False), + ("first", "base", False), + ("base", "first", False), + ("first", "alias", True), + ("alias", "first", True), + ], +) +def test_setup_ownership_distinguishes_environments_sharing_an_interpreter( + tmp_path: Path, selected_name: str, cli_name: str, matches: bool +) -> None: + for name in ("first", "second"): + venv.EnvBuilder(with_pip=False, symlinks=True).create(tmp_path / name) + (tmp_path / "alias").symlink_to(tmp_path / "first", target_is_directory=True) + interpreters = { + name: tmp_path / name / "bin" / "python" for name in ("first", "second", "alias") + } + interpreters["base"] = interpreters["first"].resolve() + selected, cli = interpreters[selected_name], interpreters[cli_name] + # This is the old false-positive condition, shared by every test case. + assert selected.resolve() == cli.resolve() + + evidence, status = _run_ownership_probe(selected, cli) + identities = json.loads(evidence) + assert identities["selected"]["executable"] == str(selected) + assert identities["cli"]["executable"] == str(cli) + if selected_name != cli_name: + assert identities["selected"]["prefix"] != identities["cli"]["prefix"] + assert status == ( + "matches selected Python" if matches else "CLI belongs to another Python environment" + ) + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX executable launcher fixture") +@pytest.mark.parametrize("failure", ["missing", "invalid-json", "nonzero"]) +def test_setup_ownership_probe_failure_remains_unverified(tmp_path: Path, failure: str) -> None: + cli = tmp_path / "broken-python" + if failure != "missing": + cli.write_text( + f"#!{sys.executable}\n" + + ("print('not JSON')\n" if failure == "invalid-json" else "exit(1)\n") + ) + cli.chmod(0o755) + output = _run_ownership_probe(Path(sys.executable), cli) + assert output[0].startswith("CLI ownership unverified:") + assert not any("matches selected Python" in line for line in output) + + +def test_setup_ownership_contract_requires_identity_and_preserves_shebang_semantics() -> None: + skill = SKILL_PATH.read_text() + assert "resolve `` in the current `PATH` without dereferencing symlinks" in skill + assert "including `env -S`" in skill + assert "do not drop arguments and probe a different invocation" in skill + ready_definition = next(line for line in skill.splitlines() if line.startswith("- `ready`:")) + assert "CLI help succeeds" in ready_definition + assert "normalized `sys.executable` and `sys.prefix`" in ready_definition