Skip to content

perf(cli): stop the daemon fast path importing polylogue.api/ArchiveStore - #3517

Merged
Sinity merged 3 commits into
masterfrom
perf/defer-api-import-daemon-fastpath
Aug 1, 2026
Merged

Sinity merged 3 commits into
masterfrom
perf/defer-api-import-daemon-fastpath

Conversation

@Sinity

@Sinity Sinity commented Aug 1, 2026

Copy link
Copy Markdown
Owner

Summary

A daemon-served find (or any query command the daemon can serve) paid the
full cold-start import cost of polylogue.api, ArchiveStore,
surfaces.payloads, and search_providers even though the daemon served the
request over UDS and none of those modules were ever touched. This PR defers
all of them to the local-execution fallback path, and fixes a related
AppEnv.config/.runtime inefficiency that forced the same cost via a
different route.

Problem

Evidence (bead polylogue-g3jk, filed from PR #3507's perf audit — #3507 was
still open/unmerged at the time of this work, so this branch targets current
master directly and does not depend on it):

  • Cold polylogue find <q> paid ~2s beyond --help's baseline even when a
    daemon served the request over UDS in ~50ms — the daemon fast path
    (_try_emit_daemon_session_page in cli/archive_query.py) saved query
    execution but not import tax.
  • Three compounding eager-import sources, found by tracing the actual call
    graph (not guessing):
    1. cli/query.py imported polylogue.api.sync.bridge.run_coroutine_sync at
      module scope. Importing any submodule of polylogue.api forces Python to
      execute polylogue/api/__init__.py first (the whole Polylogue facade —
      pydantic viewport/surface models, storage repository mixins), even though
      the sync bridge itself only needs asyncio/threading.
    2. cli/archive_query.py imported ArchiveStore, surfaces.payloads,
      search_providers, archive.stats, and the attached-units/unit-results
      helpers at module top — all exclusively used by the local-execution
      fallback, but paid on every import of the module regardless of whether
      the daemon fast path ever reaches that fallback.
    3. AppEnv.config/.runtime routed through AppEnv.services
      (_lazy_services → polylogue.services → storage.repository →
      storage.sqlite), which imports the full repository/backend stack merely
      to hand back a Config projection RuntimeServices.__post_init__ had
      already computed from runtime.as_config(). load_effective_config(env)
      is the first thing _execute_archive_query_stdout calls, before the
      daemon-try — this was actually the single largest remaining cost after
      fixing (1) and (2), found by tracing sys.modules deltas through a mocked
      daemon-success call.

Solution

  • New polylogue/core/async_bridge.py holds the real run_coroutine_sync
    implementation (dependency-free: only asyncio/threading).
    polylogue/api/sync/bridge.py now re-exports it for existing callers that
    already depend on the Polylogue facade (Lynchpin, MCP, etc. are
    unaffected); cli/query.py imports the light module directly.
  • archive_query.py's local-execution-only imports move under
    TYPE_CHECKING (safe because they're annotation-only under from __future__ import annotations) plus function-local imports at each real
    call site: mutation emitters (_emit_mutation/_emit_user_mutations/
    _emit_delete), vector search (_query_hits), unit-source rows
    (_emit_unit_source_rows/_unit_source_session_filters), attached units
    (_inject_attached_units), cursor encode/decode (_decode_cursor/
    _build_cursor), session-detail rendering (_emit_stream,
    _session_summary_text), and list/search row payloads
    (_summary_payload/_hit_payload).
  • AppEnv.config/.runtime (cli/shared/types.py) return
    self._runtime/self._runtime.as_config() directly when .services was
    never built, instead of forcing it. click_app.py already constructs
    AppEnv(runtime=runtime, ...) with no explicit services=, so this is the
    real production shape every CLI invocation hits, not a synthetic corner
    case — verified by grepping every AppEnv( construction site.

Non-goals / residual cost: archive.query.expression/archive.query.spec
(the query DSL compiler) still cost real import time (dateparser,
polylogue.archive.viewport.models pydantic classes, polylogue.storage.search_providers)
— these are used identically by both the daemon and local-execution paths to
compile the query before either path runs, so deferring them wouldn't be
daemon-fast-path-specific and is out of scope here. This is the "diffuse
pydantic model construction, no single lazy-import fix left" the bead already
flagged for the query-compilation layer specifically (as opposed to the
local-execution layer this PR addresses).

Verification

Measurement method note: this workstation runs a live production
polylogued daemon against a real personal archive (systemd --user polylogued.service). Two attempts at live-CLI/live-daemon E2E timing during
this work both leaked real archive content into command output because (a)
the daemon UDS socket path ($XDG_RUNTIME_DIR/polylogue/daemon.sock) is
machine-wide, not archive-root-scoped, so a second daemon on a custom archive
root never actually gets used — the CLI always finds the live daemon's
socket; and (b) even explicit --no-daemon local execution through the real
polylogue binary did not honor POLYLOGUE_ARCHIVE_ROOT and hit the live
archive. Both are pre-existing, separate bugs (matching/extending the
already-tracked polylogue-z9gh / polylogue-tas4 "two surfaces disagree about
FTS readiness" finding — worth a dedicated follow-up, since (b) is worse than
previously documented: it reproduces even without a daemon involved). No
writes occurred (find is read-only) and the live daemon/archive were
unaffected (verified via systemctl --user status polylogued.service
before/after — same PID, same start time throughout). All further
measurement in this PR uses an in-process harness
(execute_query_request driven directly against a tmp_path archive with a
monkeypatched _fetch_daemon_sessions_payload) plus the existing
tests/unit/cli/test_daemon_golden_parity.py real-UDS-daemon-in-a-thread
pattern — never the live daemon or a shell subprocess against ambient env
vars.

Before/after (in-process harness, git apply -R/git apply roundtrip on
this exact diff to get a clean A/B on identical hardware):

before after
total wall time 2.88s 1.31s
polylogue.api imported True False
archive_tiers.archive imported True False
archive_tiers.write imported True False
surfaces.payloads imported True False
search_providers imported True True (unavoidable, see Non-goals)

Commands run:

  • python -m mypy polylogue tests → Success: no issues found in 2263 source files
  • python -m ruff check polylogue tests / ruff format --check → clean
  • python -m devtools test tests/unit/cli/test_daemon_fastpath_import_cost.py tests/unit/cli/test_app_env_config_fastpath.py tests/unit/cli/test_archive_query.py tests/unit/api/test_sync_bridge.py → 111 passed
  • python -m devtools test tests/unit/cli/test_daemon_golden_parity.py (real UDS daemon in a background thread, byte-identical direct-vs-daemon-proxied output contract) → 3 passed
  • python -m devtools render topology-projection (required: new polylogue/core/async_bridge.py module) → committed docs/plans/topology-target.yaml
  • python -m devtools verify --quick → exit_code: 0 (ran twice, once locally and once via the pre-push hook)

Anti-vacuity: reverted this exact diff (git apply -R) and reran both new
tests — all three assertions fail as expected:

  • test_daemon_served_query_does_not_import_heavy_local_execution_stack →
    heavy modules leaked into the daemon fast path: polylogue.api,polylogue.services,polylogue.storage.repository,polylogue.storage.sqlite.archive_tiers.archive,polylogue.storage.sqlite.archive_tiers.write,polylogue.surfaces.payloads
  • test_config_returns_runtime_projection_without_building_services /
    test_runtime_property_returns_the_same_object_without_building_services →
    AssertionError: assert RuntimeServices(...) is None (i.e. .services got
    built when it shouldn't have)

The production caller exercised is the real dispatch chain: click_app.py's
_handle_query_mode → cli/query.py:execute_query_request →
cli/archive_query.py:execute_archive_query →
_try_emit_daemon_session_page, with AppEnv constructed exactly as
click_app.py constructs it (runtime=, no explicit services=).

AC matrix

Acceptance criterion Status
Investigate exact import chain for polylogue.api eager import Satisfied — traced to cli/query.py's module-level polylogue.api.sync.bridge import
Defer polylogue.api import until after the daemon fast-path decision Satisfied — core/async_bridge.py split, query.py no longer touches polylogue.api
Restructure query-mode dispatch (light preflight module vs. full local executor) Partially satisfied via a different mechanism — rather than physically splitting archive_query.py into two modules, its local-execution-only imports were converted to TYPE_CHECKING + function-local imports at their call sites. Same runtime effect (heavy modules never load unless the miss path executes) without the larger risk of a structural file split mid-function (the fast-path check is threaded through a 700-line function that also does shared query-spec compilation).
Target ~0.7-0.9s daemon-served cold find Not fully met — measured 1.31s in the in-process harness. The residual cost is archive.query.expression/archive.query.spec (dateparser, viewport pydantic models), used identically by both daemon and local paths for query-DSL compilation, out of scope for a daemon-fast-path-specific fix. Filing a follow-up for that layer (see below).
Real before/after timing Satisfied, via the safe in-process harness described above (live-CLI/live-daemon timing was unsafe on this host — see Verification)
Import-graph contract test, anti-vacuity proof Satisfied — test_daemon_fastpath_import_cost.py + test_app_env_config_fastpath.py, both verified to fail when the fix is reverted

Follow-ups (not filed as beads from this lane — bd is read-only here; reporting to the coordinator)

  • The --no-daemon / real-archive-root env-var-precedence bug reproduced
    during this work (real archive content served even with an explicit
    --no-daemon flag and a different POLYLOGUE_ARCHIVE_ROOT) deserves a
    dedicated investigation — it's more severe than the previously tracked
    polylogue-z9gh/polylogue-tas4 daemon-only finding.
  • archive.query.expression/archive.query.spec's own import cost
    (dateparser, viewport pydantic models) is a separate, larger effort (would
    need polylogue.core.dates/archive.viewport.viewports to defer
    dateparser/pydantic construction) if the ~0.7-0.9s target is still wanted.

Ref polylogue-g3jk

@coderabbitai

coderabbitai Bot commented Aug 1, 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: 15 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: 04699be8-fa97-4765-8e0c-916e36ca85fe

📥 Commits

Reviewing files that changed from the base of the PR and between e39492c and 2bf741b.

📒 Files selected for processing (8)
  • docs/plans/topology-target.yaml
  • polylogue/api/sync/bridge.py
  • polylogue/cli/archive_query.py
  • polylogue/cli/query.py
  • polylogue/cli/shared/types.py
  • polylogue/core/async_bridge.py
  • tests/unit/cli/test_app_env_config_fastpath.py
  • tests/unit/cli/test_daemon_fastpath_import_cost.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.

@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: 7d177bd065

ℹ️ 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/archive_query.py Resolved
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 and others added 2 commits August 1, 2026 15:05
…tore

Problem: a daemon-served `find` paid the full ~1.7-2.8s polylogue.api
import cost (pydantic viewport/surface models, storage repository
mixins) even though the daemon served the request over UDS and the CLI
never touched ArchiveStore, the Polylogue facade, or any local-execution
renderer. Three eager-import sources compounded:

1. cli/query.py imported `polylogue.api.sync.bridge.run_coroutine_sync`
   at module scope. Importing any submodule of `polylogue.api` forces
   Python to execute polylogue/api/__init__.py first, even though the
   sync bridge itself only needs asyncio/threading.
2. cli/archive_query.py imported ArchiveStore, surfaces.payloads,
   search_providers, archive.stats, and the attached-units/unit-results
   helpers at module top -- all local-execution-only, but paid on every
   import of the module regardless of whether the daemon fast path
   (_try_emit_daemon_session_page) ever reaches the local-execution
   fallback.
3. AppEnv.config/.runtime routed through AppEnv.services (_lazy_services
   -> polylogue.services -> storage.repository -> storage.sqlite),
   which imports the full repository/backend stack merely to hand back
   a Config projection RuntimeServices.__post_init__ already computed
   from runtime.as_config(). load_effective_config(env) is the first
   thing archive_query.py's main function calls, before the daemon-try.

Solution:
- New polylogue/core/async_bridge.py holds the actual run_coroutine_sync
  implementation (dependency-free). polylogue/api/sync/bridge.py now
  re-exports it for existing callers that already depend on the
  Polylogue facade; cli/query.py imports the light module directly.
- archive_query.py's local-execution-only imports move under
  TYPE_CHECKING (annotation-only uses, safe under `from __future__
  import annotations`) plus function-local imports at each real call
  site (mutation emitters, vector search, unit-source rows, attached
  units, cursor encode/decode, session-detail rendering).
- AppEnv.config/.runtime return `self._runtime`/`self._runtime.as_config()`
  directly when `.services` was never built, instead of forcing it.
  click_app.py already constructs `AppEnv(runtime=runtime, ...)`, so
  this is the real production shape, not a synthetic corner case.

Verification (in-process harness driving execute_query_request through a
mocked daemon-success response, since this workstation's live
`polylogued` daemon and archive make CLI-subprocess timing unsafe to
reproduce here -- see PR body):
  before: total 2.88s, heavy modules imported: polylogue.api=True,
    archive_tiers.archive=True, archive_tiers.write=True,
    surfaces.payloads=True, search_providers=True
  after:  total 1.31s, heavy modules imported: polylogue.api=False,
    archive_tiers.archive=False, archive_tiers.write=False,
    surfaces.payloads=False, search_providers=True (structural
    dependency of archive.query.expression, shared by both paths,
    out of scope here)

New tests:
- tests/unit/cli/test_daemon_fastpath_import_cost.py: subprocess-based
  behavioral contract (pattern from #3507's
  test_drift_marker_import_path_stays_light) asserting the forbidden
  modules never land in sys.modules after a mocked daemon-success query.
- tests/unit/cli/test_app_env_config_fastpath.py: AppEnv.config/.runtime
  fast-path + explicit-services backward-compat + no-runtime-no-services
  error path.

Ref polylogue-g3jk

Co-Authored-By: Claude <[email protected]>
@Sinity
Sinity force-pushed the perf/defer-api-import-daemon-fastpath branch from 7d177bd to 90d7870 Compare August 1, 2026 13:07
The daemon fast-path import-cost deferral moved ArchiveStore and
create_vector_provider to TYPE_CHECKING + function-local imports. A
function-local import binds a name that shadows the module attribute,
so both unittest.mock.patch("polylogue.cli.archive_query.ArchiveStore...")
and .create_vector_provider silently stopped intercepting calls -
43 tests in test_query_exec_laws.py plus the CodeRabbit-flagged
create_vector_provider case broke.

create_vector_provider becomes a persistent module-level function that
does its heavy import lazily inside the call; ArchiveStore gets a PEP
562 module __getattr__ so `archive_query.ArchiveStore` resolves lazily
without an eager import at module load, while both patch targets keep
working. Neither name is evaluated at runtime elsewhere in this module
(from __future__ import annotations, TYPE_CHECKING-only otherwise), so
the daemon fast path still never imports ArchiveStore/search_providers.

Ref polylogue-g3jk.
Sinity added a commit that referenced this pull request Aug 1, 2026
Problem: across a ~28-PR merge train in one coordinator session
(2026-08-01), two incidents showed operator memory doesn't scale as
the sole safety net before squash-merging. PR #3502 merged with 0
review comments showing at check time; CodeRabbit posted 3 real
findings 30-60s later (caught only by an ad hoc grace-period poll
habit adopted afterward). PR #3517 nearly merged carrying a 43-test
regression that no CI check or review comment ever flagged, since
per-PR CI deliberately skips the heavy test suite (CLAUDE.md) -
caught only because the coordinator happened to run the broader
local suite by hand before merging that specific time.

What changed: `devtools workspace merge-gate record <PR> --command
"..."` runs a local verification command against a PR's current head
sha and persists a receipt keyed to that exact sha under
.cache/verify/merge-gate/. `merge-gate check <PR>` BLOCKs unless a
fresh, exit-0 receipt exists for the PR's CURRENT head (a new push
invalidates the old receipt) and no review comment's created_at is
newer than the head commit's timestamp - late comments are listed
explicitly rather than requiring a human to compare two timestamps
by hand. This doesn't replace judgment about what a late comment
means; it makes an unverified late signal impossible to merge past
silently.

Verification: devtools test tests/unit/devtools/test_merge_gate.py
(9 passed, covering fresh/stale-sha/late-comment/closed-PR/expired-
receipt cases against a faked gh subprocess). Live smoke test against
open PR #3517: record + check round-tripped correctly (BLOCK before
recording, OK after). devtools verify --quick exit 0.
Sinity added a commit that referenced this pull request Aug 1, 2026
CodeRabbit review on merge-gate's own PR (#3518) found real gaps:

1. record() only copied the fetched head_sha into the receipt without
   verifying the local checkout was actually AT that commit -- a
   receipt could attest to unrelated code (e.g. recording from master
   or a stale worktree). Now refuses (exit 2) unless `git rev-parse
   HEAD` matches the PR's headRefOid and the tree is clean.

2. The documented example used `devtools verify --quick`, which
   explicitly skips tests -- the exact profile that would have missed
   PR #3517's 43-test regression, this tool's own motivating incident.
   Fixed the example to `devtools verify`, and record() now tags a
   receipt with skips_tests: true when the command looks like it
   didn't run tests (heuristic), which check() surfaces as an
   advisory.

3. check() took a single comment snapshot, so a comment posted 30-60s
   later (the PR #3502 incident this tool exists to prevent) could
   still slip through if check() ran before it landed. check() now
   polls comments across a configurable grace window (default 3x20s)
   instead of one snapshot.

4. Once a comment's created_at was later than the head commit, it
   blocked forever with no way to mark it triaged short of an empty
   commit. Added `ack <PR> <comment-id> --reason "..."`, scoped to the
   PR's current head sha so a new push always re-requires triage.

Verification: devtools test tests/unit/devtools/test_merge_gate.py
-- 16 passed (added: checkout-mismatch refusal, dirty-tree refusal,
skips_tests flagging, multi-round poll catching a comment that only
appears on round 2, ack suppressing a late comment for its exact head
sha but not a different one). devtools verify --quick exit 0.
@Sinity
Sinity merged commit 4ae1473 into master Aug 1, 2026
3 checks passed
@Sinity
Sinity deleted the perf/defer-api-import-daemon-fastpath branch August 1, 2026 13:53
Sinity added a commit that referenced this pull request Aug 1, 2026
daemon fast-path import-cost deferral landed (2.88s->1.31s cold find).
Sinity added a commit that referenced this pull request Aug 1, 2026
Problem: across a ~28-PR merge train in one coordinator session
(2026-08-01), two incidents showed operator memory doesn't scale as
the sole safety net before squash-merging. PR #3502 merged with 0
review comments showing at check time; CodeRabbit posted 3 real
findings 30-60s later (caught only by an ad hoc grace-period poll
habit adopted afterward). PR #3517 nearly merged carrying a 43-test
regression that no CI check or review comment ever flagged, since
per-PR CI deliberately skips the heavy test suite (CLAUDE.md) -
caught only because the coordinator happened to run the broader
local suite by hand before merging that specific time.

What changed: `devtools workspace merge-gate record <PR> --command
"..."` runs a local verification command against a PR's current head
sha and persists a receipt keyed to that exact sha under
.cache/verify/merge-gate/. `merge-gate check <PR>` BLOCKs unless a
fresh, exit-0 receipt exists for the PR's CURRENT head (a new push
invalidates the old receipt) and no review comment's created_at is
newer than the head commit's timestamp - late comments are listed
explicitly rather than requiring a human to compare two timestamps
by hand. This doesn't replace judgment about what a late comment
means; it makes an unverified late signal impossible to merge past
silently.

Verification: devtools test tests/unit/devtools/test_merge_gate.py
(9 passed, covering fresh/stale-sha/late-comment/closed-PR/expired-
receipt cases against a faked gh subprocess). Live smoke test against
open PR #3517: record + check round-tripped correctly (BLOCK before
recording, OK after). devtools verify --quick exit 0.
Sinity added a commit that referenced this pull request Aug 1, 2026
CodeRabbit review on merge-gate's own PR (#3518) found real gaps:

1. record() only copied the fetched head_sha into the receipt without
   verifying the local checkout was actually AT that commit -- a
   receipt could attest to unrelated code (e.g. recording from master
   or a stale worktree). Now refuses (exit 2) unless `git rev-parse
   HEAD` matches the PR's headRefOid and the tree is clean.

2. The documented example used `devtools verify --quick`, which
   explicitly skips tests -- the exact profile that would have missed
   PR #3517's 43-test regression, this tool's own motivating incident.
   Fixed the example to `devtools verify`, and record() now tags a
   receipt with skips_tests: true when the command looks like it
   didn't run tests (heuristic), which check() surfaces as an
   advisory.

3. check() took a single comment snapshot, so a comment posted 30-60s
   later (the PR #3502 incident this tool exists to prevent) could
   still slip through if check() ran before it landed. check() now
   polls comments across a configurable grace window (default 3x20s)
   instead of one snapshot.

4. Once a comment's created_at was later than the head commit, it
   blocked forever with no way to mark it triaged short of an empty
   commit. Added `ack <PR> <comment-id> --reason "..."`, scoped to the
   PR's current head sha so a new push always re-requires triage.

Verification: devtools test tests/unit/devtools/test_merge_gate.py
-- 16 passed (added: checkout-mismatch refusal, dirty-tree refusal,
skips_tests flagging, multi-round poll catching a comment that only
appears on round 2, ack suppressing a late comment for its exact head
sha but not a different one). devtools verify --quick exit 0.
Sinity added a commit that referenced this pull request Aug 1, 2026
…3518)

## Summary

Adds `devtools workspace merge-gate`, replacing coordinator memory
(grace-period
comment polling, remembering to run the broader local test suite per-PR
CI
skips) with a check that fails closed.

## Problem

Two incidents in a single ~28-PR merge-train session (2026-08-01):
1. PR #3502 was squash-merged with 0 review comments showing at check
time;
   CodeRabbit posted 3 real findings 30-60s later.
2. PR #3517 nearly merged carrying a 43-test regression that no CI check
or
review comment ever flagged (per-PR CI deliberately skips the heavy test
   suite — see CLAUDE.md). It was caught only because the coordinator
happened to run the broader local suite by hand before merging that
time.

A coordinator merging dozens of PRs across a few hours cannot reliably
repeat
either habit purely from memory every single time.

## Solution

- `devtools workspace merge-gate record <PR> --command "..."` runs a
local
  verification command against the PR's current head sha and persists a
  receipt keyed to that exact sha under `.cache/verify/merge-gate/`.
- `devtools workspace merge-gate check <PR>` BLOCKs unless a fresh,
exit-0
receipt exists for the PR's CURRENT head (a new push invalidates the old
  receipt) and no review comment's `created_at` is newer than the head
  commit's timestamp — late comments are listed explicitly instead of
  requiring a human to compare timestamps by hand.

Does not replace judgment about what a late finding means — makes an
unverified late signal impossible to merge past silently.

## Verification

`devtools test tests/unit/devtools/test_merge_gate.py` — 9 passed (fresh
receipt, stale-sha, late-comment, closed-PR, expired-receipt cases
against a
faked `gh` subprocess). Live smoke test against open PR #3517: `check`
BLOCKed
before recording, then `record` + `check` round-tripped to OK. `devtools
verify --quick` exit 0.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **New Features**
  * Added a merge-gate command for pre-merge verification.
  * Records local verification results tied to the current change.
* Checks verification freshness, change status, and recent review
comments.
  * Supports acknowledging valid review-comment exceptions.
* Provides human-readable and JSON verdicts with configurable polling
and receipt age.

* **Documentation**
  * Added usage guidance and CLI examples for the merge-gate workflow.

* **Tests**
* Added comprehensive coverage for verification, freshness, review
comments, acknowledgements, and failure scenarios.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Sinity added a commit that referenced this pull request Aug 3, 2026
## Summary

Adds `devtools workspace merge <PR>`, a wrapper around `gh pr merge
--squash` that structurally enforces the existing `merge-gate`
record/check safety net and the merge-train terminal full-suite-verify
rule, instead of leaving both as steps a coordinator has to remember to
invoke.

## Problem

`devtools workspace merge-gate record/check` (merge_gate.py) and the
CLAUDE.md rule "run one full-suite `devtools verify --all` per
merge-train session" are both real, already-shipped fixes for real
2026-08-01 incidents:

- PR #3502 was squash-merged with 0 review comments visible; CodeRabbit
posted 3 real findings 30-60s later.
- PR #3517 nearly merged carrying a 43-test regression that no CI check
and no review comment ever flagged (per-PR CI deliberately skips the
heavy suite).

Both fixes work, but only if a coordinator remembers to invoke them at
the right moment mid-session. The fanout-operations report's
incident-ledger cross-check (referenced by beads `polylogue-ct3r2` and
`polylogue-t6iga`, which are duplicate filings of the same finding)
found the exact pattern: fixes that became a *command* stuck; fixes that
stayed a memory-triggered *rule* recurred at least once.

There is no GitHub Actions hook available to attach enforcement to here
-- this repo's CI is CircleCI-only, GHA is intentionally dark. The
actual merge boundary in practice is a human/agent coordinator invoking
`gh pr merge --squash`, so that is the wrapping point.

## Solution

`devtools/merge_boundary.py`, registered as `devtools workspace merge`
in `devtools/command_catalog.py`:

- `merge <PR>`: refuses unless the PR is `OPEN`; if no fresh merge-gate
receipt exists for the current head sha, auto-records one (running
`--command`, default `devtools verify`) instead of just erroring; runs
`merge-gate check` and refuses to merge on any BLOCK (stale/missing
receipt, nonzero exit, unacked late review comment); applies title
hygiene by stripping a doubled `(#N) (#N)` squash-subject suffix (the
2026-07-12/13 incident where a manual `gh pr edit --title` step was
skipped); then runs the actual `gh pr merge --squash`. `--dry-run` runs
every check without merging. `--with-verify` immediately runs and
records the merge-train's terminal full-suite verify after merging.
- `train-status`: reports (exit 1) any PRs merged since the last
recorded full-suite verify, reading a ledger at
`.cache/verify/merge-gate/merge-train-ledger.json` -- the structural
stand-in for "a merge-train records the full-suite verify as its
terminal ledger step."
- `record-full-verify --command "devtools verify --all"`: runs and
records that terminal step directly, clearing the ledger's pending list.

CLAUDE.md's merge-checklist bullet ("Before squash-merging any PR") now
names `workspace merge` as the command to actually use, rather than
describing the two-step `merge-gate record`/`check` sequence as
something the coordinator must remember to run in order.

The lower-level `merge-gate record/check/ack` commands are untouched and
still usable directly for ad hoc receipt inspection; `merge` is a thin,
tested composition on top of them (`cmd_record`/`cmd_check` are called
directly, not re-implemented).

## Verification

- `devtools test tests/unit/devtools/test_merge_boundary.py
tests/unit/devtools/test_merge_gate.py` -> 35 passed (decision-logic
tests mock `subprocess.run`/`gh` boundaries per the existing
`test_merge_gate.py` pattern: receipt fresh/stale/absent, unacked newer
review comment, title-hygiene collapse/append/idempotence, dry-run never
calling `gh pr merge`, ledger append/pending-PR detection,
`record-full-verify` clearing pending state).
- `python -m mypy devtools/merge_boundary.py
tests/unit/devtools/test_merge_boundary.py` -> no issues.
- `devtools verify --quick` -> exit_code 0 (ruff format/check, mypy
--strict, `render all --check`, topology/layering/manifests/lab-policy
gates all ok).
- `devtools render topology-projection` / `devtools render
devtools-reference` were run and their outputs
(`docs/plans/topology-target.yaml`, `docs/devtools.md`) are included in
this diff.

Not run: `devtools verify --all` (full non-integration suite) -- left
for the coordinator's merge-train terminal step, consistent with what
this PR itself builds.

Ref polylogue-ct3r2, polylogue-t6iga -- both bead filings describe the
same recommendation; this PR implements it once. The coordinator should
dedupe the two beads (close one as duplicate-of-the-other, or close both
against this PR) rather than tracking the same follow-up twice.

Co-Authored-By: Claude <[email protected]>

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

  • 58.F060 / P1: fixed-already at the checked revision: tests/unit/cli/test_embed_activation.py:897 now injects the vector backend through DaemonReadDependencies.vector_provider. The affected tests no longer patch the removed CLI module symbol, and exercise the replacement operation-backed search path.

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