Skip to content

fix(devtools): refuse to run when polylogue resolves outside the checkout - #3475

Merged
Sinity merged 2 commits into
masterfrom
feature/devtools/worktree-import-guard
Jul 31, 2026
Merged

Sinity merged 2 commits into
masterfrom
feature/devtools/worktree-import-guard

Conversation

@Sinity

@Sinity Sinity commented Jul 31, 2026

Copy link
Copy Markdown
Owner

Summary

A shared linked-worktree venv can silently resolve import polylogue to a
different checkout than the one invoking it. This PR adds a structural
guard that refuses (loudly, naming both paths) instead of running, wires it
into every entry point that can plausibly hit the hazard, and prints the
resolved package path as part of devtools verify/devtools test receipts.

Problem

A linked git worktree without its own .venv reuses the main checkout's
shared venv on PATH. That venv's editable install (a .pth in
site-packages) points at the main checkout, so a plain import polylogue
with nothing else on sys.path silently resolves there instead of the
worktree's own source — no ImportError, just wrong code answering every
question while looking exactly like a genuine result.

This corrupted four separate lanes in one day (2026-07-30/31):

  1. A performance lane's entire "after" measurement set measured master
    instead of its own branch; caught mid-session, had to retract and redo.
  2. Another lane got false "still timing out" CLI readings, resolved only by
    pinning sys.path explicitly.
  3. devtools lab policy schema-versioning reported an impossible
    contradiction — comparing the MAIN checkout's INDEX_SCHEMA_VERSION
    against the WORKTREE's delta declarations.
  4. A benchmark run needed per-run module.__file__ printing as a manual
    guard.

Reproduced directly: a standalone script run via python3 /realm/tmp/x.py
from inside a worktree resolves polylogue.__file__ to the main checkout,
even with the worktree as cwd, because the script's own directory (not
cwd) becomes sys.path[0] and nothing else on the path favors the
worktree over the shared venv's editable .pth.

Solution

devtools/checkout_guard.py is a single shared resolver (same shape as
devtools.verify_runs.resolve_pytest_basetemp_root, which PR #3449 used to
fix a structurally identical two-implementations-disagreeing bug): it
asserts polylogue.__file__ resolves inside a given checkout root, and
raises CheckoutImportMismatchError naming both paths plus remediation
otherwise.

Wired into every entry point that can plausibly hit the hazard:

  • devtools/click_dispatch.py:main() — the CLI entry point refuses (exit
    125) before dispatching any command.
  • devtools/verify.py:main() / devtools/run_tests.py:main() — refuse
    before running any step, and print the resolved polylogue path as part
    of the run receipt (new VerifyRun.polylogue_import_path field, surfaced
    in .cache/verify/current-run.json).
  • tests/conftest.py:pytest_configure — refuses via pytest.UsageError, so
    even a bare pytest/python -m pytest invocation that skips devtools
    entirely still catches it (tests/conftest.py is always collected for any
    pytest run rooted at this repo).

Environmental layer, costed honestly: the flake devShell already gives
every checkout its own .venv (uv venv + uv sync, keyed off $PWD) via
direnv allow — that's the fully correct fix and is already
correct-by-construction per worktree. Its cost is a multi-minute sync plus a
few hundred MB of disk per worktree, which is presumably why short-lived
agent worktrees reuse the shared venv instead of paying that cost per spin-up.
Changing that bootstrap behavior is outside this repo (it's harness/operator
infra, not polylogue code), so this PR does not attempt it; the tradeoff is
documented in CLAUDE.md instead.

Residual gap: a standalone ad hoc script that never imports devtools or
pytest has no hook to run the check from. Documented in CLAUDE.md; such a
script can call devtools.checkout_guard.assert_polylogue_matches_checkout
itself in one line for the same guarantee.

CLAUDE.md's Gotchas section is updated with the hazard writeup, what's now
guarded, and the residual gap — the guard is the fix, the doc explains it.

Verification

  • devtools verify --quick — all 18 steps green, including
    lab policy schema-versioning (the exact check that produced an
    "impossible" contradiction in the incident), now printing
    verify: polylogue package → .../worktrees/.../polylogue/__init__.py.
  • devtools test tests/unit/devtools/test_checkout_guard.py — 7/7 passed:
    match case, mismatch case (both paths named in the message), a
    sibling-directory near-miss (guards against a weaker string-prefix
    regression of the Path.relative_to check), and each of the three wired
    entry points refusing with exit 125 on a monkeypatched mismatch.
  • devtools test tests/unit/devtools/test_run_tests.py tests/unit/devtools/test_devtools_main.py tests/unit/devtools/test_cli_wrapper.py
    — 26/26 passed, no regressions in the wired entry points' existing tests.
  • Manual demonstration of a genuine refusal: loaded
    devtools/checkout_guard.py by file path with no worktree entry on
    sys.path (reproducing the real hazard against the shared venv's ambient
    main-checkout resolution) and confirmed CheckoutImportMismatchError
    fires, naming both the worktree checkout and the resolved main-checkout
    package path, with the remediation text.
  • ruff format --check / ruff check / mypy --strict — clean on all
    touched files.
  • devtools render topology-projection — regenerated
    docs/plans/topology-target.yaml for the new devtools/checkout_guard.py
    module; devtools render all --check reports no drift.

Not run: the full test suite (per-PR CI skips it). A directory-wide
devtools test tests/unit/devtools/ sweep (run once, against the repo's own
anti-pattern guidance, to sanity-check breadth) surfaced 5 pre-existing
failures in test_lineage_validation.py, test_render_quality_reference.py,
and test_verify_demo_tour_freshness.py — none in files this change
touches, reproducing identically at -n 0 (not an xdist artifact), unrelated
to the import-guard change.

…kout

Problem: a linked git worktree without its own .venv reuses the main
checkout's shared venv. That venv's editable install (.pth) points at the
main checkout, so a plain `import polylogue` with nothing else on sys.path
silently resolves there instead of the worktree's own source -- no
ImportError, just wrong code answering every question while looking like a
genuine result. This corrupted four separate lanes in one day (2026-07-30/31):
a perf "after" measurement, false CLI-timeout readings, an "impossible"
schema-version contradiction in `devtools lab policy schema-versioning`, and a
benchmark needing manual sys.path pinning.

What changed: devtools/checkout_guard.py is a single shared resolver (same
shape as devtools.verify_runs.resolve_pytest_basetemp_root / PR #3449) that
asserts `polylogue.__file__` resolves inside a given checkout root and raises
CheckoutImportMismatchError naming both paths plus remediation otherwise.
Wired into every entry point that can plausibly hit the hazard:
  - devtools/click_dispatch.py:main() -- the CLI entry point refuses (exit
    125) before dispatching any command.
  - devtools/verify.py:main() / devtools/run_tests.py:main() -- refuse before
    running any step, and print the resolved polylogue path as part of the
    run receipt (new VerifyRun.polylogue_import_path field, surfaced in
    .cache/verify/current-run.json).
  - tests/conftest.py:pytest_configure -- refuses via pytest.UsageError, so
    even a bare `pytest`/`python -m pytest` invocation that skips devtools
    entirely still catches it (tests/conftest.py is always collected for any
    pytest run rooted at this repo).

Residual gap (documented in CLAUDE.md): a standalone ad hoc script that never
imports devtools or pytest has no hook to run the check from. The flake
devShell already gives every checkout its own .venv via `direnv allow`
(uv venv + uv sync keyed off $PWD), which is the fully correct fix, but its
multi-minute sync + disk cost is why short-lived agent worktrees reuse the
shared venv instead -- not favorable to force here.

Verification:
  devtools verify --quick (ruff format/check, mypy --strict, render all
    --check, topology/layering/closure-matrix/schema-versioning etc.) -- all
    green, and `lab policy schema-versioning` (the exact check that produced
    an "impossible" contradiction in the incident) now prints
    "verify: polylogue package → .../worktrees/.../polylogue/__init__.py".
  devtools test tests/unit/devtools/test_checkout_guard.py -- 7/7 passed,
    including regression coverage for the raise path (both paths named),
    a sibling-directory near-miss, and each wired entry point refusing on a
    monkeypatched mismatch.
  Manual demonstration: loaded devtools/checkout_guard.py by file path with
  no worktree entry on sys.path (reproducing the real hazard against the
  shared venv's ambient main-checkout resolution) and confirmed
  CheckoutImportMismatchError fires naming both the worktree checkout and the
  resolved main-checkout package path.
  devtools test tests/unit/devtools/test_run_tests.py
    tests/unit/devtools/test_devtools_main.py tests/unit/devtools/test_cli_wrapper.py
    -- 26/26 passed (no regressions in the wired entry points' existing tests).

Not run: full test suite (per-PR CI skips it; a directory-wide
tests/unit/devtools/ sweep surfaced 5 pre-existing failures in
test_lineage_validation.py, test_render_quality_reference.py, and
test_verify_demo_tour_freshness.py -- none in files this change touches,
reproduce identically at -n 0, unrelated to the import-guard change).

Co-Authored-By: Claude <[email protected]>
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

@coderabbitai

coderabbitai Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

@Sinity, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 17 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 045e40a1-0424-4dd7-a6f0-97ee25b6e3ad

📥 Commits

Reviewing files that changed from the base of the PR and between dc98d3a and 0402731.

📒 Files selected for processing (9)
  • CLAUDE.md
  • devtools/checkout_guard.py
  • devtools/click_dispatch.py
  • devtools/run_tests.py
  • devtools/verify.py
  • devtools/verify_runs.py
  • docs/plans/topology-target.yaml
  • tests/conftest.py
  • tests/unit/devtools/test_checkout_guard.py

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.

@Sinity
Sinity merged commit 0283052 into master Jul 31, 2026
1 of 3 checks passed
@Sinity
Sinity deleted the feature/devtools/worktree-import-guard branch July 31, 2026 16:30
Sinity added a commit that referenced this pull request Aug 1, 2026
… section (#3501)

## Summary

Orchestration-machinery hardening from the 2026-08-01 fanout audit: a
new `devtools workspace verify-worktree` command that catches the
worktree-isolation-escape failure mode before a lane's output is
trusted, a `lane-brief` "Recently merged on master (footprint overlap)"
section with an explicit PRIOR-SATISFACTION CHECK, standing-hazard
updates (no background idle-waits, no lane-side bd writes), and a
`.agent/CONVENTIONS.md` fix that scopes background execution to
coordinator sessions only.

## Problem

Four verified failure modes from the 2026-08-01 20-lane fanout (each
re-verified against source/git, not taken from the incident narrative):

1. An `isolation: "worktree"` dispatch silently ran in the main checkout
and left ~1700 uncommitted lines in the coordinator's live tree; no
tooling existed to verify a lane's claimed worktree (confirmed via the
devtools command catalog).
2. Lane agents' bd calls from stale worktrees reverted 5+ live
coordinator bead writes twice (polylogue-2ara, P1 open). Live evidence
in this lane: a plain `git switch -c` inside the worktree fired the
beads post-checkout JSONL import. Note:
`feature/devtools/worktree-import-guard` is NOT this fix — its commit
f51f373 is content-identical to merged PR #3475 (checkout_guard); the
branch is superseded and deletable. Remaining polylogue-2ara scope:
bd-invocation-time skip-import-if-older.
3. Three lanes stalled for multiple turns idle-waiting on backgrounded
`devtools test` runs — and `.agent/CONVENTIONS.md` itself recommended
"long test runs ... go to background execution".
4. Lane polylogue-2cuv burned its budget on a bead already satisfied by
a same-session merge; the brief's per-path last-3-commits crumbs did not
surface this.

Incidents 5/6 (master-red via narrow gates, repaired in #3498/#3500) are
assessed in the companion memo as a process-economics tradeoff,
deliberately not addressed with new tooling here.

## Solution

- `devtools/verify_worktree.py` (+ catalog entry, regenerated
`docs/devtools.md`): hard checks — path exists, inside a git repo, is a
LINKED worktree (`--absolute-git-dir` vs `--git-common-dir`), toplevel
distinct from the main checkout, `--expect-branch` match; advisory
checks — uncommitted changes, stale `.beads/issues.jsonl` (max
`updated_at` vs main checkout, string-comparable ISO-8601). `--json`,
`--strict`, exit 1 on hard failure.
- `devtools/lane_brief.py`: `_recent_master_commits()` aggregates `git
log --since=N days origin/master -- <footprint paths>` into a dedicated
section headed by a PRIOR-SATISFACTION CHECK instruction; new
`--recent-days`; hazards now forbid background idle-waits and lane-side
bd writes (polylogue-2ara).
- `.agent/CONVENTIONS.md`: async execution scoped to coordinator
sessions; new coordinator dispatch-hygiene bullet (run verify-worktree
after every spawn).

Companion memo (out-of-blast-radius recommendations, incl. sinnix
doctrine edits):
`.agent/scratch/2026-08-01-orchestration-audit-recommendations.md`
(gitignored; copy preserved in the session scratchpad).

## Verification

- `devtools test tests/unit/devtools/test_verify_worktree.py
tests/unit/devtools/test_lane_brief.py` — `24 passed in 5.18s`.
- Live smoke: `devtools workspace verify-worktree <this lane's worktree>
--expect-branch feature/devtools/orchestration-audit` → `verdict: OK`;
`devtools workspace verify-worktree /realm/project/polylogue` → `[FAIL]
linked_worktree ... MAIN checkout`, exit 1.
- `devtools verify --quick` — exit 0 (87.3s, all 18 steps green).
- Not run: full suite / `verify --all` (no substrate code touched;
testmon-affected + focused tests cover the changed surface).

## Anti-vacuity

The verify-worktree tests build real git repos + `git worktree add` and
exercise real `git rev-parse` semantics — dropping the
git-dir/common-dir comparison flips
`test_main_checkout_fails_isolation_check`; dropping the `updated_at`
comparison flips `test_stale_beads_jsonl_is_flagged`. The production
caller is the coordinator dispatch flow documented in
`.agent/CONVENTIONS.md` (and exercised live in this PR's verification).
`test_render_markdown_prior_satisfaction_warning_lists_recent_commits`
fails if the new section is dropped from `_render_markdown`.

Ref polylogue-2ara.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01P7dQJSbhvx7LSu5PW9Ns9S

---------

Co-authored-by: Claude Sonnet 5 <[email protected]>
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