Repository navigation
fix(coverage): hoist env prefixes off testCmd, refuse the unsafe ones - #97
Conversation
The tests gate runs testCmd through `sh -c`, where `PYTHONPATH=. pytest` is an environment assignment. The coverage runner spawns argv directly and had no concept of one, so it classified the assignment as a module name and emitted `coverage run -m PYTHONPATH=. python3 ...`. Nothing was imported, no data file was written, and the verdict capped at UNPROVEN. The tests gate stayed green throughout, so the failure was invisible, and `PYTHONPATH=` is our own documented remedy for shadow bypass. Every project following that advice could never reach SAFE. Leading assignments are now hoisted into the child environment and the remainder classifies as before. Hoisting stops at the first token that is not an assignment, so `pytest -k a=b` keeps its argument. COVERAGE_FILE is applied after the hoisted vars so a test command cannot redirect the data file, which would look exactly like measuring nothing. A value containing `$` is declined rather than hoisted. The shell would expand it and this path would not, and a coverage run over a different sys.path than the verified run is worse than no measurement. Closes #95
Review found that the previous commit introduced a false SAFE, which is the one defect this project treats as unforgivable. Reproduced: an edit making add(2, 3) return -1 read SAFE with 'PYTHONPATH=<repoRoot> pytest -q' while the module-form control read UNSAFE. Rewriting a console entry point to module form is not equivalent to the gate's spawn. `-m` puts CWD first on sys.path, ahead of PYTHONPATH, while the console script the gate runs does not. With an import-affecting variable set, that selects a different copy of the code: the gate proved the original tree green, coverage proved the shadow tree exercised, and fusing two true statements about two trees yielded SAFE. That combination is now declined. The form the docs teach, module form on both sides, stays equivalent and keeps working. Tilde is declined alongside $, since a shell expands it per path segment in an assignment value. Measurement failures now carry their reason through to coverage.unknownReason, which tool-reference already promises and which made this class of failure indistinguishable from a suite that simply never ran the code. The rule the module is governed by is now stated as a rule: return non-null only when the argv and env are observationally equivalent to what the gate's shell would have run. Tests: the adversarial case moves to a flat layout, where the divergence is reachable at all, and asserts a breaking edit can never read SAFE. Both new guards proven by mutation rather than by diffing against main, which cannot work here because the return shape changed. The shadow-bypass guard gets its first test since it shipped.
📝 WalkthroughWalkthroughCoverage commands now preserve leading environment assignments during Python coverage execution. Unsupported shell expansion and import-affecting console-command prefixes remain unwrapped. Verification retains coverage failure reasons and tests shadow-tree attribution. ChangesCoverage environment and verification
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant TestCommand
participant toCoverageRunArgs
participant CoverageRunner
participant CoverageData
TestCommand->>toCoverageRunArgs: command text with leading assignments
toCoverageRunArgs->>CoverageRunner: args and merged environment
CoverageRunner->>CoverageData: run coverage with forced COVERAGE_FILE
CoverageData-->>CoverageRunner: coverage measurement result
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (4)
tests/integration/coverage-reporter.test.ts (2)
388-392: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winPin
argstoo, not onlyenv, for the invalid-name cases.Lines 391-392 assert only
.env. For1BAD=x python3 -m pytest -q, a shell reads1BAD=xas the command name. This implementation keeps it as the first token and classifies it as a console entry point, soargsbecomes['-m', '1BAD=x', 'python3', '-m', 'pytest', '-q']. The current assertion passes for that argv. The comment above it claims the case protects against running a command the tests gate could never run, so the assertion should coverargs.The resulting run still degrades honestly to unknown, so this is a test-strength gap rather than a false
SAFE.💚 Proposed fix
- expect(toCoverageRunArgs('1BAD=x python3 -m pytest -q')?.env).toEqual({}); - expect(toCoverageRunArgs('-k=v python3 -m pytest -q')?.env).toEqual({}); + // Neither token is an assignment, so BOTH stay in argv and nothing is + // hoisted. Pinning `args` as well as `env` keeps a future change from + // quietly hoisting them or reclassifying the remainder. + expect(toCoverageRunArgs('1BAD=x python3 -m pytest -q')).toEqual({ + args: ['-m', '1BAD=x', 'python3', '-m', 'pytest', '-q'], + env: {}, + }); + expect(toCoverageRunArgs('-k=v python3 -m pytest -q')).toEqual({ + args: ['-m', '-k=v', 'python3', '-m', 'pytest', '-q'], + env: {}, + });🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/integration/coverage-reporter.test.ts` around lines 388 - 392, Strengthen the invalid-name cases in toCoverageRunArgs by asserting both env and args. For `1BAD=x python3 -m pytest -q` and `-k=v python3 -m pytest -q`, pin args to the expected unknown/degraded result so the tests reject treating the invalid assignment token as a runnable console entry point.
23-34: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsolidate the two prerequisite probes.
pythonHasCoverage()at lines 14-21 probes onlycoverage. The new IIFE probescoverageandpytest. Two probes with different prerequisites now gate tests in the same file. A reader cannot tell which gate applies to which test, and a later edit can attach the weaker gate to a test that needs pytest. That combination reports green while proving nothing, which is the exact failure the comment at line 25 warns about.Derive both from one probe, or drop
pythonHasCoverage()if the remaining callers need pytest as well.#!/bin/bash # Find the remaining callers of pythonHasCoverage in this file. set -euo pipefail rg -n -C3 '\bpythonHasCoverage\b|\bNO_COVERAGE\b' tests/integration/coverage-reporter.test.ts🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/integration/coverage-reporter.test.ts` around lines 23 - 34, Consolidate the prerequisite detection in the coverage reporter tests by removing the weaker pythonHasCoverage() probe if all remaining callers require pytest, and use the single coverage-plus-pytest result for every relevant skipIf gate. Update references to pythonHasCoverage and NO_COVERAGE consistently so each gated test uses the same prerequisite contract.tests/integration/verify-diff.test.ts (2)
212-215: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winThe negative string assertion can pass vacuously.
Line 215 asserts that
reasondoes not containnot exercised by any test. If a later change reworders that phrase in the verdict text, then this assertion passes without testing anything, and the comment above it presents this as the property that only the shadow-bypass guard delivers.Bind the phrase to a constant that the production code also uses, or add a positive control that proves the phrase does appear for a genuinely uncovered change. Then a rewording breaks the control instead of silently retiring this assertion.
#!/bin/bash # Locate the source of the 'not exercised by any test' phrase and check whether it is exported. set -euo pipefail rg -n -C4 'not exercised by any test' --type=ts🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/integration/verify-diff.test.ts` around lines 212 - 215, Make the assertion in the shadow-bypass verification test non-vacuous by reusing the production symbol for the uncovered-change verdict phrase, or add a positive control that verifies the phrase appears for a genuinely uncovered change. Update the test around intoOriginal.reason so production rewording causes the test suite to fail rather than silently weakening coverage.
241-259: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winThe skip gate does not prove that a
pytestconsole script exists.
NO_COVERAGEat line 25 probespython3 -c "import coverage, pytest". That proves the modules import. It does not prove that apytestexecutable is onPATH. This test is the only one that runspytestas a console script, at line 244.If pytest is importable but its entry point is not resolvable, then the gate command fails to start,
result.passedis false,assessCoveragenever runs, andcoverage.unknownReasonstays undefined. Line 259 then fails onString(undefined)for an environment reason, not for the behavior under test.Add a console-script probe and gate this test on it.
💚 Proposed fix
+// This suite's console-script case spawns `pytest` as an EXECUTABLE, which +// `import pytest` does not prove is on PATH. +function hasPytestScript(): boolean { + try { + execSync('pytest --version', { stdio: 'ignore' }); + return true; + } catch { + return false; + } +} +const NO_PYTEST_SCRIPT = !hasPytestScript();- it.skipIf(NO_COVERAGE)( + it.skipIf(NO_COVERAGE || NO_PYTEST_SCRIPT)( 'a change that BREAKS the suite can never read SAFE, whatever the prefix',🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/integration/verify-diff.test.ts` around lines 241 - 259, Update the skip setup for this integration test to probe whether the pytest console script is resolvable on PATH, in addition to the existing NO_COVERAGE module-import check. Gate the test using that console-script probe so it is skipped when `pytest` cannot be launched, while preserving the existing `viaConsoleScript` and `viaModuleForm` assertions when the command is available.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@tests/integration/coverage-reporter.test.ts`:
- Around line 266-268: Update the skipped integration test “hoists through a
real coverage run, keeping the inherited env” to provide an explicit timeout
matching the nearby integration test pattern, ensuring the full subprocess flow
including coverage json is covered by the 30000ms budget.
---
Nitpick comments:
In `@tests/integration/coverage-reporter.test.ts`:
- Around line 388-392: Strengthen the invalid-name cases in toCoverageRunArgs by
asserting both env and args. For `1BAD=x python3 -m pytest -q` and `-k=v python3
-m pytest -q`, pin args to the expected unknown/degraded result so the tests
reject treating the invalid assignment token as a runnable console entry point.
- Around line 23-34: Consolidate the prerequisite detection in the coverage
reporter tests by removing the weaker pythonHasCoverage() probe if all remaining
callers require pytest, and use the single coverage-plus-pytest result for every
relevant skipIf gate. Update references to pythonHasCoverage and NO_COVERAGE
consistently so each gated test uses the same prerequisite contract.
In `@tests/integration/verify-diff.test.ts`:
- Around line 212-215: Make the assertion in the shadow-bypass verification test
non-vacuous by reusing the production symbol for the uncovered-change verdict
phrase, or add a positive control that verifies the phrase appears for a
genuinely uncovered change. Update the test around intoOriginal.reason so
production rewording causes the test suite to fail rather than silently
weakening coverage.
- Around line 241-259: Update the skip setup for this integration test to probe
whether the pytest console script is resolvable on PATH, in addition to the
existing NO_COVERAGE module-import check. Gate the test using that
console-script probe so it is skipped when `pytest` cannot be launched, while
preserving the existing `viaConsoleScript` and `viaModuleForm` assertions when
the command is available.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: 6dec2792-0637-4f54-9fb5-5bf4ca0c543f
📒 Files selected for processing (4)
src/analyze/coverage/python-line-coverage.tssrc/verify/verify-diff.tstests/integration/coverage-reporter.test.tstests/integration/verify-diff.test.ts
| it.skipIf(NO_COVERAGE)( | ||
| 'hoists through a real coverage run, keeping the inherited env', | ||
| async () => { |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Check the configured Vitest test timeout for integration tests.
set -euo pipefail
fd -i 'vitest*.config.*|vite.config.*' --exec rg -n -C5 'testTimeout|hookTimeout|include|projects|workspace' {}
rg -n -C2 'testTimeout' --iglob 'package.json'Repository: Refactron-ai/Refactron_Lib_TS
Length of output: 1714
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== candidate integration test files =="
fd -i 'verify-diff\.test\.ts|coverage-reporter\.test\.ts|package\.json|vitest.*config.*|vite.*config.*' .
echo
echo "== package test scripts =="
python3 - <<'PY'
import json
from pathlib import Path
p=Path('package.json')
data=json.load(open(p))
print(json.dumps(data.get('scripts', {}), indent=2))
PY
echo
echo "== testTimeout declarations =="
rg -n -C3 '"vitest"|"testTimeout|testTimeout|scripts"
testTimeout|vite.config|vitest.config' -S package.json tests .github 2>/dev/null || trueRepository: Refactron-ai/Refactron_Lib_TS
Length of output: 1775
Set an explicit timeout on this subprocess test.
This test spawns coverage run over pytest; configure timeout is 30000, but the related coverage json subprocess is not part of that budget. Add the explicit timeout, matching the nearby integration test pattern.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@tests/integration/coverage-reporter.test.ts` around lines 266 - 268, Update
the skipped integration test “hoists through a real coverage run, keeping the
inherited env” to provide an explicit timeout matching the nearby integration
test pattern, ensuring the full subprocess flow including coverage json is
covered by the 30000ms budget.
Closes #95.
What
The coverage runner now understands a leading
NAME=VALUEprefix ontestCmd, and refuses the cases where honouring it would measure a different run than the gate verified.Why
Refactron runs your suite twice, and the two paths disagreed about what a command is.
The tests gate hands it to a shell:
src/verify/runners/detect.ts:27spawnssh -c "<cmd>", soPYTHONPATH=. python3 -m pytest -qis an environment assignment and the tests run correctly.The coverage runner spawns argv, because
coverage runtakes argv. Its classifier had no concept of an assignment, soPYTHONPATH=.fell through to the console-entry-point branch:Nothing was imported, no data file was written, and the verdict capped at
UNPROVEN. The tests gate stayed green, so nothing looked broken; you simply never reachedSAFE, on every run.That matters because
PYTHONPATH=is our own documented remedy for shadow bypass (docs/verification/verdicts.mdx:209). Over MCP it is the only form available:src/mcp/tools/verify-change.ts:15declarestestCmdas a plain string with no env field, and nine pages underdocs/mcp/instruct agents to use the prefix.Before and after, same repo, same edit, same suite, only
testCmddiffers:Review found a false SAFE in the first commit. Read this part.
The first commit made verdicts that were previously
UNPROVENable to reachSAFE. That is the dangerous direction, and it went wrong exactly there. Reproduced on a flat-layout project with an edit that makesadd(2, 3)return-1:testCmdmainPYTHONPATH=<repoRoot> pytest -qUNPROVEN(fail-safe)PYTHONPATH=<repoRoot> pytest -qSAFE— "Tests pass and the changed code is covered."python3 -m pytest -q(control)UNSAFE— the edit really does break the suiteRewriting a console entry point to module form is not equivalent to the gate's spawn:
The gate proved the original tree green while coverage proved the shadow tree exercised. Both statements true, about different trees, fused into
SAFE. Hoisting the environment is what made that pre-existing argv divergence reachable in-band.That combination is now declined. Module form is equivalent on both sides, so
PYTHONPATH=. python3 -m pytest -q— the form the docs teach and the issue's own repro — keeps working. Widening the decline can only lose capability; narrowing it loses soundness.The rule this module now states
It is written into the module header, because the alternative is learning one shell feature per bug report. Under it, this PR is not "the argv path grew a feature" but "a construct we can prove equivalent stopped being declined". An ADR should follow.
Also declined for the same reason: values containing
$, and values where a shell would expand~(at the start, or after any:, since expansion applies per path segment).Silent declines are the bug, so declines now explain themselves
reportCoveragecomputescannot wrap test command for coverage: ..., anddocs/mcp/tool-reference.mdx:103promises agents thatcoverage.unknownReasonsays why coverage is unknown when we know it.verify-diff.tsdiscarded it. An agent writingPYTHONPATH=$PWD/srcwould have hit the new decline and received the identical unhelpful message it got before this fix, which is #95's failure mode reintroduced by #95's fix. The reason is now carried through.Evidence
Run on
8bd0d88:Locked contracts untouched.
VerdictReportunchanged: no field added, renamed, retyped or removed, noreportVersionbump.toCoverageRunArgschanges return type, but there is nosrc/index.tsat all andpackage.jsonexportshas no subpath patterns, so it is unreachable by any consumer.reportCoverage's other caller,src/analyze/engine.ts:99, passes notestCmd; confirmed unaffected bytests/integration/preflight.test.ts, which reaches it with notestCmdand assertscoverageAvailable.Red-first, by mutation
Diffing against
maincannot prove the classifier tests red: the return shape changed, so every assertion fails onmainwhether or not it tests anything. Each guard was verified by mutating this branch instead:Genuinely red on
mainfor behavioural reasons:hoists a leading NAME=VALUE prefix(received["-m","PYTHONPATH=.","python3","-m","pytest","-q"]),PYTHONPATH= prefix still measures coverage(expected 'none' to be 'coverage.py'), and the env-merge test against stashed pre-fix source.Four further guards were added because a mutation run showed the suite survived without them: quoted assignment values with whitespace, later-assignment-wins, non-identifier names such as
1BAD=x, and a pin on the defaultpytest -qclassification.A note on the shadow-bypass guard
It shipped in round-4 (#86) with no test, and the whole suite passed with it neutered. It now has one. Its contract is not the verdict — a file missing from
measuredFileshas no covered lines, so the per-file AND incoverage-attribution.tsalready forcesUNPROVEN. What only the guard delivers is refusing to say "the changed code is not exercised by any test" about code the suite was never given the chance to load. That sentence is the assertion now pinned.Not verified locally
Windows.
sh -cstrips backslashes in an assignment value, so the new tests normalise fixture paths to forward slashes and assertgates.tests.passedto stop a mangled path from passing theUNPROVENassertions for the wrong reason. Whether backslash-bearing hoisted values should be declined outright is a follow-up.Follow-ups, deliberately not in this PR
SAFEonmainby the same mechanism out of band:export PYTHONPATH=<repoRoot>plustestCmd: pytest -q. This PR does not create or widen it; it needs its own issue.$decline to all tokens, not just hoisted values, plus ansh-differential test harness that comparestoCoverageRunArgsagainst a real shell.unknownReasonof their own.package.jsonadvertises a.export resolving to a file the build never produces.coverage-reporter.test.tsthat report PASSED.Summary by CodeRabbit