Repository navigation
fix(cli): guard the polylogue console script against wrong-checkout imports - #3512
Conversation
…mports Problem: devtools/checkout_guard.py's worktree-import protection covers devtools/__main__.py, devtools verify/test, and tests/conftest.py, but not the installed `polylogue`/`plg` console scripts. A linked git worktree without its own .venv reuses the main checkout's shared editable install, so `import polylogue` silently resolves to a DIFFERENT checkout's code — confirmed live: an audit lane's `polylogue --version` reported the main checkout's dirty commit while its own `git rev-parse HEAD` showed a different commit, with no warning anywhere in the CLI's output. Solution: wire assert_polylogue_matches_checkout into polylogue/cli/click_app.py's main(), gated behind a new find_git_worktree_root() helper in devtools/checkout_guard.py. Unlike the existing call sites, click_app.py's own __file__ cannot anchor "the invoking checkout" -- if the hazard already occurred, this file itself is the wrong checkout's copy. The trustworthy anchor is the process's cwd: find_git_worktree_root() does a cheap, subprocess-free walk up from cwd for a .git entry, and the guard no-ops when cwd has no git ancestry (a real installed-tool invocation) or POLYLOGUE_ALLOW_WORKTREE_ESCAPE=1 is set, matching the existing bypass convention used by the worktree-escape pre-commit hook. Verified cheap (relevant given #3507, landed the same day, cutting CLI cold-start import tax): `python -X importtime -m polylogue --help` shows devtools.checkout_guard at 508us cumulative against a ~580ms total --help invocation. Verification: - devtools test tests/unit/cli/test_click_app_main.py tests/unit/devtools/test_checkout_guard.py -- 15 passed, including three new regression tests: guard fires on mismatch (exit 125, no stdout), no-ops with no git ancestry, bypassed by POLYLOGUE_ALLOW_WORKTREE_ESCAPE=1. - devtools verify --quick -- exit 0 (format, lint, mypy, render-check, layering, degrade-loudly, closure-matrix, hash-boundary-census, schema-versioning, promotion audit). - devtools verify (testmon default) refused: pytest-testmon is unseeded in this worktree (fresh checkout, never ran --seed-testmon). Not run given the seeding cost; the two focused test files above cover every line this change touches. Anti-vacuity: removing the `_guard_checkout_or_exit()` call from click_app.py's main() (or removing assert_polylogue_matches_checkout from inside it) makes test_main_refuses_on_checkout_mismatch fail -- SystemExit(125) would never be raised and the command would proceed to dispatch normally. Ref polylogue-6mgg Co-Authored-By: Claude <[email protected]>
📝 WalkthroughWalkthroughThe change adds filesystem-based Polylogue checkout detection and integrates it into CLI startup. The guard compares the imported package checkout with the current Git checkout, supports non-Git and bypass cases, and exits with status 125 on mismatch. ChangesCheckout guard
Estimated code review effort: 3 (Moderate) | ~20 minutes Sequence Diagram(s)sequenceDiagram
participant CLI as click_app.main()
participant Guard as _guard_checkout_or_exit()
participant Root as find_git_worktree_root()
participant Dispatch as CLI dispatch
CLI->>Guard: validate current checkout
Guard->>Root: locate enclosing Polylogue checkout
Root-->>Guard: return checkout root or None
alt matching checkout or bypass
Guard-->>CLI: allow execution
CLI->>Dispatch: dispatch arguments
else checkout mismatch
Guard-->>CLI: report error and exit 125
end
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 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.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2a9414c8c7
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
Problem: PR #3512's polylogue-cli-checkout-guard added find_git_worktree_root() to protect the bare `polylogue` console script against the shared-venv worktree-import hazard, but it walked up from cwd to find ANY `.git` root and treated it unconditionally as "the invoking Polylogue checkout". Running `polylogue` from any unrelated git repo (a normal end-user scenario: `cd ~/my-other-project && polylogue --version`) made the mismatch guard fire and exit 125 for every single command, because that unrelated repo obviously doesn't contain the installed polylogue package. Reproduced with the pre-fix implementation against a scratch git repo (devtools/checkout_guard.py:HEAD) before applying this change. Solution: find_git_worktree_root() now only returns a discovered `.git` ancestor when it also looks like a Polylogue checkout (_is_polylogue_checkout_root(), checking pyproject.toml's [project].name or the polylogue/cli/click_app.py marker file). An unrelated git repo's root is treated the same as "no git ancestry at all" -- both no-op the guard, matching the existing devtools/pytest entry points' behavior (which anchor on their own trustworthy __file__ and were never affected by this bug). The linked-Polylogue-worktree-hijack case PR #3512 exists to catch is untouched: that root still passes the checkout marker check and the mismatch assertion still fires. Verification: - python -m devtools test tests/unit/cli/test_click_app_main.py tests/unit/devtools/test_checkout_guard.py -> 18 passed (adds 3 new regression tests: unrelated-git-repo no-op, no-git-ancestry no-op, and the real-checkout happy path; existing PR #3512 regression tests for the mismatch/no-ancestry/escape-var cases still pass unchanged). - python -m devtools verify --quick -> exit_code 0. - Manual repro: `cd` into a throwaway `git init`'d directory and run `python -m polylogue --version` -- exit 125 with the pre-fix code, exit 0 (prints version) with this fix. Ref polylogue-373yt, polylogue-6mgg. Co-Authored-By: Claude <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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/unit/cli/test_click_app_main.py`:
- Around line 140-145: Strengthen the checkout-guard tests by making
find_git_worktree_root in test_main_refuses_on_checkout_mismatch assert that its
argument equals Path.cwd(), and make it raise AssertionError in
test_main_bypasses_guard_with_escape_env_var. Keep the existing mismatch and
escape assertions unchanged while verifying the guard uses the process working
directory and bypasses checkout detection when the environment variable is set.
🪄 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: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro Plus
Run ID: 4dc0a8d8-fdca-4eda-bb5f-6170e7bfe64d
📒 Files selected for processing (4)
devtools/checkout_guard.pypolylogue/cli/click_app.pytests/unit/cli/test_click_app_main.pytests/unit/devtools/test_checkout_guard.py
| def _boom(repo_root: Path, *, context: str) -> Path: | ||
| raise CheckoutImportMismatchError(f"{context}: mismatch against {repo_root}") | ||
|
|
||
| monkeypatch.setattr(click_app, "find_git_worktree_root", lambda start: Path("/some/worktree")) | ||
| monkeypatch.setattr(click_app, "assert_polylogue_matches_checkout", _boom) | ||
| monkeypatch.delenv("POLYLOGUE_ALLOW_WORKTREE_ESCAPE", raising=False) |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win
Assert the checkout-guard control flow.
In test_main_refuses_on_checkout_mismatch, make the fake find_git_worktree_root assert that it receives Path.cwd(). The current lambda accepts any path, so a regression to a module-derived path would pass.
In test_main_bypasses_guard_with_escape_env_var, make find_git_worktree_root raise AssertionError. The current test proves that assert_polylogue_matches_checkout is skipped, but it does not prove that the bypass skips checkout detection.
Proposed test change
+ def _find_worktree_root(start: Path) -> Path:
+ assert start == Path.cwd()
+ return Path("/some/worktree")
+
- monkeypatch.setattr(click_app, "find_git_worktree_root", lambda start: Path("/some/worktree"))
+ monkeypatch.setattr(click_app, "find_git_worktree_root", _find_worktree_root)+ def _unexpected_find_worktree_root(start: Path) -> Path | None:
+ raise AssertionError("find_git_worktree_root must not run when escape is set")
+
- monkeypatch.setattr(click_app, "find_git_worktree_root", lambda start: Path("/some/worktree"))
+ monkeypatch.setattr(click_app, "find_git_worktree_root", _unexpected_find_worktree_root)Based on PR objectives, the guard must use the process working directory and skip checks for the escape variable.
Also applies to: 185-190
🤖 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/unit/cli/test_click_app_main.py` around lines 140 - 145, Strengthen the
checkout-guard tests by making find_git_worktree_root in
test_main_refuses_on_checkout_mismatch assert that its argument equals
Path.cwd(), and make it raise AssertionError in
test_main_bypasses_guard_with_escape_env_var. Keep the existing mismatch and
escape assertions unchanged while verifying the guard uses the process working
directory and bypasses checkout detection when the environment variable is set.
…socket and demo-hardening findings Merged PR #3511 (polylogue-3b607) and PR #3512 (polylogue-373yt), closed both. Filed polylogue-kadx3 (P0: daemon UDS socket path not archive-scoped, found live during PR #3517 perf work) and polylogue-dl6af (3 new review findings on PR #3516's demo self-heal guard). Closed PR #3515 as superseded by #3516.
|
Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.
Only the rows listed above are dispositioned. Held findings remain open. |
Summary
Wires
devtools/checkout_guard.py's worktree-import protection into the installedpolylogue/plgconsole scripts, which were the one entry point a cold agent (or an MCP/daemon launcher shelling out topolylogue) is most likely to invoke directly, and the one entry point the guard didn't cover.Problem
devtools/checkout_guard.py'sassert_polylogue_matches_checkoutcloses the shared-venv worktree-import hazard (2026-07-30/31: a linked git worktree without its own.venvreuses the main checkout's editable install, soimport polyloguesilently resolves to a different checkout's code) fordevtools/__main__.py,devtools verify/devtools test, andtests/conftest.py. It was never wired intopolylogue/cli/click_app.py.Confirmed live: an audit lane running
polylogue --versionfrom inside a.claude/worktrees/<id>linked worktree reported the main checkout's dirty commit, whilegit rev-parse HEADin that same worktree showed a different commit — everypolylogue find/status/demo/...command in that session had silently exercised the wrong checkout's code and schema expectations, with nothing in the CLI's own output flagging the mismatch.Solution
devtools/checkout_guard.py: newfind_git_worktree_root(start)— a pure filesystem.git-entry walk up fromstart, no subprocess, cheap enough for every invocation. Documented in the module docstring alongside the existing wiring list, explaining why this entry point needs a different anchor than the others.polylogue/cli/click_app.py: new_guard_checkout_or_exit(), called first thing inmain(). Unlike the existing call sites (whose own__file__is a trustworthy anchor because they're only ever reached via a real path onsys.path),click_app.py's own__file__is the resolvedpolyloguepackage — if the hazard already occurred, this file is already the wrong checkout's copy, so it can't self-certify. The trustworthy anchor is the process's cwd instead:find_git_worktree_root(Path.cwd())names the checkout the operator actually intended (theycd'd into the worktree and ranpolylogue ...there). No-ops when cwd has no git ancestry (a real installed-tool invocation) orPOLYLOGUE_ALLOW_WORKTREE_ESCAPE=1is set — reusing the existing bypass convention from the worktree-escape pre-commit hook.tests/unit/cli/test_click_app_main.py: three regression tests — guard fires on mismatch (exit 125, no stdout produced), no-ops with no git ancestry, bypassed byPOLYLOGUE_ALLOW_WORKTREE_ESCAPE=1.Cold-start cost:
python -X importtime -m polylogue --helpshowsdevtools.checkout_guardat 508us cumulative against a ~580ms total--helpinvocation — negligible, relevant because #3507 (merged the same day) specifically cut CLI cold-start import tax and I rebased onto it before finishing this change.Verification
devtools test tests/unit/cli/test_click_app_main.py tests/unit/devtools/test_checkout_guard.py— 15 passed (8 + 7, including the 3 new tests).devtools verify --quick— exit 0 (format, lint, mypy, render-check, layering, degrade-loudly, closure-matrix, hash-boundary-census, schema-versioning, promotion audit); also ran again automatically via the pre-push hook after rebasing onto origin/master.devtools verify(testmon default) refused: pytest-testmon is unseeded in this worktree (fresh checkout that never ran--seed-testmon). Not run given the seeding cost for a two-file change; the focused runs above cover every line touched.click_app.py:main()now catches once the fix is on the running checkout.AC matrix
click_app.py:main()→_guard_checkout_or_exit()).CheckoutImportMismatchErrortype, same stderr message shape, same exit code 125..gitworktree is detected andPOLYLOGUE_ALLOW_WORKTREE_ESCAPEis unset" — satisfied.tests/unit/devtools/test_checkout_guard.py's own monkeypatch pattern.Anti-vacuity
Production entry point exercised:
polylogue.cli.click_app.main(), the function bound to thepolylogue/plgconsole-script entry points inpyproject.toml. Mutation that breaks the test: removing the_guard_checkout_or_exit()call frommain()(or removing theassert_polylogue_matches_checkoutcall from inside that helper) makestest_main_refuses_on_checkout_mismatchfail —SystemExit(125)would never be raised and the (mocked) mismatch would go undetected, silently falling through to normal command dispatch.Ref polylogue-6mgg
Summary by CodeRabbit
New Features
polyloguecommand runs from the same Git checkout where it was installed.POLYLOGUE_ALLOW_WORKTREE_ESCAPE=1.Bug Fixes