Skip to content

fix(cli): guard the polylogue console script against wrong-checkout imports - #3512

Merged
Sinity merged 2 commits into
masterfrom
feature/fix/polylogue-cli-checkout-guard
Aug 1, 2026
Merged

Sinity merged 2 commits into
masterfrom
feature/fix/polylogue-cli-checkout-guard

Conversation

@Sinity

@Sinity Sinity commented Aug 1, 2026 •

Copy link
Copy Markdown
Owner

Summary

Wires devtools/checkout_guard.py's worktree-import protection into the installed polylogue/plg console scripts, which were the one entry point a cold agent (or an MCP/daemon launcher shelling out to polylogue) is most likely to invoke directly, and the one entry point the guard didn't cover.

Problem

devtools/checkout_guard.py's assert_polylogue_matches_checkout closes the shared-venv worktree-import hazard (2026-07-30/31: a linked git worktree without its own .venv reuses the main checkout's editable install, so import polylogue silently resolves to a different checkout's code) for devtools/__main__.py, devtools verify/devtools test, and tests/conftest.py. It was never wired into polylogue/cli/click_app.py.

Confirmed live: an audit lane running polylogue --version from inside a .claude/worktrees/<id> linked worktree reported the main checkout's dirty commit, while git rev-parse HEAD in that same worktree showed a different commit — every polylogue 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: new find_git_worktree_root(start) — a pure filesystem .git-entry walk up from start, 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 in main(). Unlike the existing call sites (whose own __file__ is a trustworthy anchor because they're only ever reached via a real path on sys.path), click_app.py's own __file__ is the resolved polylogue package — 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 (they cd'd into the worktree and ran polylogue ... there). No-ops when cwd has no git ancestry (a real installed-tool invocation) or POLYLOGUE_ALLOW_WORKTREE_ESCAPE=1 is 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 by POLYLOGUE_ALLOW_WORKTREE_ESCAPE=1.

Cold-start cost: python -X importtime -m polylogue --help shows devtools.checkout_guard at 508us cumulative against a ~580ms total --help invocation — 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.
  • Manual repro check: ran the (unpatched, main-checkout) installed console script from this worktree's cwd and confirmed it still silently resolves to the main checkout's code — matches the bug report exactly, and is exactly the case this PR's click_app.py:main() now catches once the fix is on the running checkout.

AC matrix

  • "Wire assert_polylogue_matches_checkout (or equivalent) into polylogue CLI's entry point" — satisfied (click_app.py:main() → _guard_checkout_or_exit()).
  • "Match the existing guard's error/exit-code contract" — satisfied: same CheckoutImportMismatchError type, same stderr message shape, same exit code 125.
  • "Gate so it only fires when a .git worktree is detected and POLYLOGUE_ALLOW_WORKTREE_ESCAPE is unset" — satisfied.
  • "Regression test proving the guard fires (mock/simulate)" — satisfied, following tests/unit/devtools/test_checkout_guard.py's own monkeypatch pattern.
  • "Verify no meaningful cold-start regression" — satisfied, measured negligible (~0.5ms of ~580ms).

Anti-vacuity

Production entry point exercised: polylogue.cli.click_app.main(), the function bound to the polylogue/plg console-script entry points in pyproject.toml. Mutation that breaks the test: removing the _guard_checkout_or_exit() call from main() (or removing the assert_polylogue_matches_checkout call from inside that helper) makes test_main_refuses_on_checkout_mismatch fail — 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

    • Added a safety check to ensure the polylogue command runs from the same Git checkout where it was installed.
    • Commands now stop with a clear error and exit status 125 when a checkout mismatch is detected.
    • The check is skipped outside Git repositories and can be explicitly bypassed with POLYLOGUE_ALLOW_WORKTREE_ESCAPE=1.
  • Bug Fixes

    • Prevents commands from unintentionally running against a different working tree.

…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]>
@coderabbitai

coderabbitai Bot commented Aug 1, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The 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.

Changes

Checkout guard

Layer / File(s) Summary
Checkout root detection and coverage
devtools/checkout_guard.py, tests/unit/devtools/test_checkout_guard.py
The guard identifies Polylogue roots from project metadata or the package entry point. It supports Git directories and files, stops at the first Git boundary, and returns no root for unrelated or non-Git paths.
CLI checkout preflight
polylogue/cli/click_app.py
main() validates the current checkout before dispatch. Approved bypasses and non-Git directories skip validation. Mismatches report to stderr and exit with status 125.
CLI guard behavior tests
tests/unit/cli/test_click_app_main.py
Tests cover mismatch termination, no Git ancestry, and POLYLOGUE_ALLOW_WORKTREE_ESCAPE=1.

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
Loading
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the primary change: guarding the polylogue console script against imports from the wrong checkout.
Description check ✅ Passed The description covers the core template sections and provides detailed implementation, verification, risks, and acceptance information.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/fix/polylogue-cli-checkout-guard

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread polylogue/cli/click_app.py Resolved
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]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 62f1d1a and bbca538.

📒 Files selected for processing (4)
  • devtools/checkout_guard.py
  • polylogue/cli/click_app.py
  • tests/unit/cli/test_click_app_main.py
  • tests/unit/devtools/test_checkout_guard.py

Comment on lines +140 to +145
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 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.

@Sinity
Sinity merged commit b12175b into master Aug 1, 2026
3 checks passed
@Sinity
Sinity deleted the feature/fix/polylogue-cli-checkout-guard branch August 1, 2026 13:00
Sinity added a commit that referenced this pull request Aug 1, 2026
…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.
@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

  • 60.F002 / P1: fixed-already at the checked revision: devtools/checkout_guard.py:85 returns a discovered Git boundary only when _is_polylogue_checkout_root accepts it; an unrelated repository returns None. The installed CLI therefore skips the checkout mismatch assertion in that case.

Only the rows listed above are dispositioned. Held findings remain open.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant