Skip to content

refactor(architecture): sqlite leak sweep, staleness unify, control-center decomposition - #2900

Merged
Sinity merged 16 commits into
masterfrom
feature/refactor/sqlite-leak-sweep-and-staleness-unify
Jul 14, 2026
Merged

Sinity merged 16 commits into
masterfrom
feature/refactor/sqlite-leak-sweep-and-staleness-unify

Conversation

@Sinity

@Sinity Sinity commented Jul 14, 2026 •

Copy link
Copy Markdown
Owner

Summary

Implements the Architecture cluster (polylogue-1r9c + a7xr features/bugs):
a source-grounded hotspot map for Polylogue's largest execution control
centers with a first coherent extraction slice landed against it, plus
six real bugs/features from the a7xr substrate-consolidation set.

Problem

Production Python grew from ~255k to ~281k lines while the largest
execution hubs (storage tier, API facade, daemon HTTP, write tier, storage
repair) kept expanding faster than the codebase average, with no committed
map of their call boundaries, ownership seams, or a prioritized
decomposition sequence. Alongside that, a cluster of real substrate bugs
and abstraction-audit findings (sqlite connection leaks, a converger/repair
staleness disagreement, dead abstractions with zero production consumers,
a hard-coded write-effects choke point) had accumulated as separately
tracked beads.

Solution

polylogue-1r9c (docs/architecture-hotspots.md, new): maps all eight
named control centers with file:line evidence, call-boundary/ownership-seam
analysis, and a prioritized extraction sequence with explicit non-goals.
Lands one coherent slice: session_annotations_write.py extracts the
self-contained session tag/work-event/phase CRUD contract out of
storage/sqlite/archive_tiers/write.py (4,595 → 4,210 lines, −8.4%), with
write.py re-exporting the same public names unchanged (no duplicate
execution path). Files seven durable child beads for the remaining seven
control centers (polylogue-redt, -u5dw, -1vzf, -gikp, -kchb,
-avmq, -w9di), each with an explicit non-goal. The layering-policy fix
this required also corrected a pre-existing, now-exposed imprecision in
archive_tiers/archive.py's raw-revision-authority twin-write contract
(a coarse tier-attribution artifact, not a behavior change).

polylogue-0aj (write-effects registry, slice 1 of 2): archive/write_effects.py's
hard-coded FTS-repair/cache-invalidation branches become a declared
WriteEffect registry (name, phase, should_run, failure_policy) that the
choke point walks generically — behavior-identical for the three existing
effects, with the phase/failure-policy declarations now explicit for future
consumers (embedding scheduling, SSE announce) to register against.

polylogue-yp0 (daemon event bus, partial — honestly not fully closed):
lands the typed in-process pub/sub core (daemon/event_bus.py, 5 event
types, full failure-isolation test coverage) but not a live producer/consumer
wiring — that's sequenced as follow-up (polylogue-14t7) per the bead's own
design note, since touching a live daemon polling loop needs its own focused
pass against the lock/starvation invariants polylogue-9e5.7 mapped.

polylogue-c9y (package-topology doctrine): docs/architecture.md's
placement rules become an 8-question decision procedure with worked
examples, plus the insights-vs-analytics vocabulary rule recorded ahead of
analytics/ landing. core/ absorbs the former top-level errors.py/
protocols.py/types.py (165 import sites updated, zero behavior change).

Prior-session work on this branch (a7xr.1/.2/.10/.13/.14/.17, all
committed before this PR turn but included here): sqlite connection-leak
sweep across ~9 sites, unified session_profile_stale_predicate between
converger and repair, killed the zero-consumer FTS5/Hybrid search-provider
lane, deleted the api/contracts shadow-adapter layer, collapsed the
one-operation operations-contract framework to concrete Import models, and
added an import-resolution drift gate for operation/artifact catalog
code_refs.

Discovered, filed, not fixed in this PR (out of scope for this
cluster, flagged rather than silently absorbed): polylogue-0puw (a stale
blob_publication_reservations row survives an ingest batch that should
drain it — confirmed pre-existing, reproduces with write_effects.py
reverted), polylogue-g99u ('codex' is not a valid Origin ValueError
in two facade contract tests — confirmed unrelated to the write-tier
extraction, the extracted code never touches origin/provider resolution),
and polylogue-ihp0 (test_fresh_user_tier_has_no_legacy_overlay_tables
asserts a stale exact table-set literal that migrations 007/008 — both
merged well before this branch's own base commit — already invalidated;
confirmed pre-existing via git merge-base --is-ancestor, unrelated to
the session_annotations_write.py extraction which the dedicated
write-tier suite proves behavior-identical, 63/63).

Rebase onto current origin/master (post-review): this branch was
3 commits behind origin/master (missing #2875/#2876/#2877) when first
opened, with GitHub reporting mergeable: CONFLICTING. Rebased cleanly;
resolved a trivial resolve-both import-block conflict in
polylogue/api/archive.py (this branch's protocols.py→core/protocols.py
move landed on the same import line master's Hermes-delivery-correlation
import touched) and regenerated the two generated-artifact conflicts
(docs/plans/topology-target.yaml, docs/topology-status.md) via
devtools render topology-projection && devtools render topology-status
rather than merging them by hand. Also closed a self-consistency gap in
polylogue-a7xr.10's own acceptance criteria: its FTS5/Hybrid provider
kill decision requires polylogue-mhx.3 to record that it now owns lane
construction now that the shared SearchProvider abstraction is gone —
that note was missing and has been appended.

Verification

  • devtools verify --quick green end to end (ruff format/check, mypy --strict,
    render all --check with zero "out of sync"/"unindexed" findings,
    topology/layering/closure-matrix/manifests/ci-workflows/doc-commands/
    test-infra-currency/test-clock-hygiene/pytest-timeout-overrides/degrade-loudly
    all pass) — run repeatedly across the session, last clean at HEAD.
  • devtools test tests/unit/archive/test_write_effects.py tests/unit/archive/test_write_gateway.py
    — 12 passed (new registry tests + full existing gateway suite).
  • devtools test tests/unit/storage/test_archive_tiers_write.py tests/unit/storage/test_archive_tiers_self_verify.py
    — 64 passed (full behavioral parity for the write-tier extraction).
  • devtools test tests/unit/storage/test_revision_replay.py — 16 passed
    (covers apply_raw_membership_classification, the entrypoint whose
    layering contract was corrected).
  • devtools test tests/unit/daemon/test_event_bus.py — 10 passed (event
    bus pub/sub core, failure isolation, immutability).
  • devtools render topology-projection && devtools render topology-status
    regenerated for every new module (session_annotations_write.py,
    daemon/event_bus.py).
  • Three pre-existing, unrelated test failures found and filed as follow-ups
    rather than silently ignored (polylogue-0puw, polylogue-g99u,
    polylogue-ihp0) — all confirmed to reproduce independent of this PR's
    changes (ihp0 additionally confirmed via git merge-base --is-ancestor to predate this branch's base commit).
  • Post-rebase re-verification: devtools verify --quick green again
    (39.76s, 15/15 steps); devtools test across the branch's new/touched
    test files (test_write_effects.py, test_event_bus.py,
    test_session_profile_staleness_predicate.py,
    test_sqlite_connection_hygiene.py, test_code_refs_resolve.py) —
    232 passed; tests/unit/storage/test_archive_tiers_write.py — 63
    passed (write-tier extraction behavioral parity, re-confirmed
    post-rebase).

Not run

Full devtools verify --all / broad directory test sweeps (per repo
policy — testmon-affected/focused selection is the default, not blanket
directory runs). Per-PR CI is disabled repo-wide (billing-locked).

@coderabbitai

coderabbitai Bot commented Jul 14, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Too many files!

This PR contains 229 files, which is 79 over the limit of 150.

To get a review, narrow the scope:
• coderabbit review --type committed # exclude uncommitted changes
• coderabbit review --dir # limit to a subdirectory
• coderabbit review --base # compare against a closer base

Upgrade to a paid plan to raise the limit.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: f670427a-c5ab-40a3-837b-736a876c3a5a

📥 Commits

Reviewing files that changed from the base of the PR and between 8916636 and a20479f.

📒 Files selected for processing (229)
  • .beads/issues.jsonl
  • CLAUDE.md
  • devtools/docs_surface.py
  • devtools/mutation_scenario_catalog.py
  • devtools/storage_correctness_scenario.py
  • devtools/synthetic_benchmark_runtime.py
  • docs/README.md
  • docs/architecture-hotspots.md
  • docs/architecture.md
  • docs/plans/campaign-coverage.yaml
  • docs/plans/layering.yaml
  • docs/plans/test-closure-matrix.yaml
  • docs/plans/test-coverage-domains.yaml
  • docs/plans/topology-target.yaml
  • docs/test-quality-workflows.md
  • docs/topology-status.md
  • polylogue/__init__.py
  • polylogue/annotations/join.py
  • polylogue/api/archive.py
  • polylogue/api/contracts/__init__.py
  • polylogue/api/contracts/api_write_surface.py
  • polylogue/api/contracts/cli_write_surface.py
  • polylogue/api/contracts/mcp_write_surface.py
  • polylogue/api/contracts/write_surface.py
  • polylogue/api/insights.py
  • polylogue/archive/filter/filters.py
  • polylogue/archive/query/archive_execution.py
  • polylogue/archive/query/expression.py
  • polylogue/archive/query/plan.py
  • polylogue/archive/query/plan_execution.py
  • polylogue/archive/query/retrieval_candidates.py
  • polylogue/archive/query/retrieval_search.py
  • polylogue/archive/query/spec.py
  • polylogue/archive/session/domain_models.py
  • polylogue/archive/session/domain_runtime.py
  • polylogue/archive/session/events.py
  • polylogue/archive/session/neighbor_candidates.py
  • polylogue/archive/session/summary_runtime.py
  • polylogue/archive/topology/edge.py
  • polylogue/archive/write_effects.py
  • polylogue/artifacts/runtime.py
  • polylogue/cli/commands/check.py
  • polylogue/cli/commands/demo.py
  • polylogue/cli/commands/embed.py
  • polylogue/cli/commands/maintenance/_assertion_export.py
  • polylogue/cli/commands/maintenance/_migrate_tier.py
  • polylogue/cli/commands/maintenance/_raw_identity.py
  • polylogue/cli/commands/maintenance/_rebuild_index.py
  • polylogue/cli/commands/paths.py
  • polylogue/cli/machine_main.py
  • polylogue/cli/query.py
  • polylogue/cli/query_actions.py
  • polylogue/cli/query_contracts.py
  • polylogue/cli/query_output.py
  • polylogue/cli/query_stats.py
  • polylogue/cli/read_views/standard.py
  • polylogue/cli/shared/check_support.py
  • polylogue/cli/shared/check_workflow.py
  • polylogue/cli/shared/embed_runtime.py
  • polylogue/cli/shared/insight_command_contracts.py
  • polylogue/config.py
  • polylogue/core/errors.py
  • polylogue/core/protocols.py
  • polylogue/core/types.py
  • polylogue/cost/plans.py
  • polylogue/daemon/backup.py
  • polylogue/daemon/convergence_stages.py
  • polylogue/daemon/convergence_standing_queries.py
  • polylogue/daemon/event_bus.py
  • polylogue/daemon/http.py
  • polylogue/demo/receipts.py
  • polylogue/insights/archive.py
  • polylogue/insights/export_bundles.py
  • polylogue/insights/registry.py
  • polylogue/insights/topology.py
  • polylogue/maintenance/replay.py
  • polylogue/mcp/server_support.py
  • polylogue/operations/__init__.py
  • polylogue/operations/import_operations.py
  • polylogue/operations/operation_contract.py
  • polylogue/operations/specs.py
  • polylogue/pipeline/ids.py
  • polylogue/pipeline/run_stages.py
  • polylogue/pipeline/services/acquisition.py
  • polylogue/pipeline/services/acquisition_persistence.py
  • polylogue/pipeline/services/indexing.py
  • polylogue/pipeline/services/ingest_batch/_core.py
  • polylogue/pipeline/services/parsing.py
  • polylogue/pipeline/services/parsing_models.py
  • polylogue/pipeline/services/parsing_workflow.py
  • polylogue/pipeline/services/planning.py
  • polylogue/pipeline/services/planning_runtime.py
  • polylogue/pipeline/services/validation.py
  • polylogue/pipeline/services/validation_flow.py
  • polylogue/pipeline/stage_specs.py
  • polylogue/schemas/validation/requests.py
  • polylogue/sources/drive/types.py
  • polylogue/sources/live/batch.py
  • polylogue/sources/live/dedup.py
  • polylogue/sources/live/watcher.py
  • polylogue/sources/sqlite_snapshot.py
  • polylogue/storage/archive_readiness.py
  • polylogue/storage/blob_gc.py
  • polylogue/storage/blob_integrity.py
  • polylogue/storage/embeddings/materialization.py
  • polylogue/storage/fts/fts_lifecycle.py
  • polylogue/storage/hydrators.py
  • polylogue/storage/index_generation.py
  • polylogue/storage/insights/session/latency_profiles.py
  • polylogue/storage/insights/session/profiles.py
  • polylogue/storage/insights/session/rebuild.py
  • polylogue/storage/insights/session/records.py
  • polylogue/storage/insights/session/run_projection_rows.py
  • polylogue/storage/insights/session/runtime.py
  • polylogue/storage/insights/session/status.py
  • polylogue/storage/insights/session/threads.py
  • polylogue/storage/insights/session/timeline_rows.py
  • polylogue/storage/insights/timeline/records.py
  • polylogue/storage/insights/topology/derivation.py
  • polylogue/storage/raw_retention.py
  • polylogue/storage/repair.py
  • polylogue/storage/repository/archive/search.py
  • polylogue/storage/repository/archive/sessions.py
  • polylogue/storage/repository/vectors/repository_vectors.py
  • polylogue/storage/runtime/__init__.py
  • polylogue/storage/runtime/archive/records.py
  • polylogue/storage/search/runtime.py
  • polylogue/storage/search_providers/__init__.py
  • polylogue/storage/search_providers/fts5.py
  • polylogue/storage/search_providers/hybrid.py
  • polylogue/storage/search_providers/hybrid_factory.py
  • polylogue/storage/search_providers/sqlite_vec_support.py
  • polylogue/storage/sqlite/archive_tiers/archive.py
  • polylogue/storage/sqlite/archive_tiers/session_annotations_write.py
  • polylogue/storage/sqlite/archive_tiers/write.py
  • polylogue/storage/sqlite/async_sqlite.py
  • polylogue/storage/sqlite/migration_runner.py
  • polylogue/storage/sqlite/queries/attachment_records.py
  • polylogue/storage/sqlite/queries/mappers_archive.py
  • polylogue/storage/sqlite/queries/mappers_insight_profiles.py
  • polylogue/storage/sqlite/queries/mappers_insight_timelines.py
  • polylogue/storage/sqlite/queries/mappers_support.py
  • polylogue/storage/sqlite/queries/session_events.py
  • polylogue/storage/sqlite/queries/session_insight_thread_queries.py
  • polylogue/storage/sqlite/queries/session_insight_timeline_reads.py
  • polylogue/storage/sqlite/queries/session_latency_profile_reads.py
  • polylogue/storage/sqlite/run_projection_relations.py
  • polylogue/storage/sqlite/schema.py
  • polylogue/ui/facade.py
  • tests/benchmarks/test_session_digest.py
  • tests/infra/archive_scenarios.py
  • tests/infra/builders.py
  • tests/infra/storage_records.py
  • tests/infra/strategies/messages.py
  • tests/infra/strategies/summaries.py
  • tests/property/test_rendering_preservation.py
  • tests/property/test_search_cursor_pagination_laws.py
  • tests/unit/api/test_facade_contracts.py
  • tests/unit/api/test_search_envelope_builder.py
  • tests/unit/api/test_write_surface_contracts.py
  • tests/unit/archive/test_coverage_diagnostics.py
  • tests/unit/archive/test_facets.py
  • tests/unit/archive/test_phase_extraction.py
  • tests/unit/archive/test_query_runtime_filters.py
  • tests/unit/archive/test_query_runtime_matching.py
  • tests/unit/archive/test_query_search_runtime.py
  • tests/unit/archive/test_repo_identity.py
  • tests/unit/archive/test_search_hits.py
  • tests/unit/archive/test_write_effects.py
  • tests/unit/cli/test_machine_main.py
  • tests/unit/cli/test_neighbors_command.py
  • tests/unit/cli/test_query_fmt.py
  • tests/unit/cli/test_query_support_runtime.py
  • tests/unit/cli/test_resume_routing.py
  • tests/unit/cli/test_select.py
  • tests/unit/core/test_config.py
  • tests/unit/core/test_json.py
  • tests/unit/core/test_models.py
  • tests/unit/core/test_semantic_facts.py
  • tests/unit/daemon/test_event_bus.py
  • tests/unit/daemon/test_schema_preflight.py
  • tests/unit/daemon/test_topology_endpoint.py
  • tests/unit/daemon/test_topology_stack.py
  • tests/unit/daemon/test_web_shell_endpoint_contracts.py
  • tests/unit/daemon/test_web_shell_reader.py
  • tests/unit/insights/test_postmortem.py
  • tests/unit/insights/test_run_projection_materialization.py
  • tests/unit/insights/test_topology_cycle_rejection.py
  • tests/unit/insights/test_transforms.py
  • tests/unit/mcp/test_embedding_retrieval_not_ready.py
  • tests/unit/mcp/test_logical_session_tool.py
  • tests/unit/mcp/test_per_tool_contracts.py
  • tests/unit/mcp/test_server_surfaces.py
  • tests/unit/mcp/test_tool_contracts.py
  • tests/unit/mcp/test_tool_error_isolation.py
  • tests/unit/operations/test_operation_contract.py
  • tests/unit/pipeline/test_ingest_append_replay.py
  • tests/unit/pipeline/test_ingest_batch.py
  • tests/unit/pipeline/test_parsing_service.py
  • tests/unit/pipeline/test_prepare.py
  • tests/unit/rendering/test_rendering.py
  • tests/unit/sinex/test_material_adapter.py
  • tests/unit/sources/test_compaction.py
  • tests/unit/sources/test_null_guard_properties.py
  • tests/unit/storage/test_archive_search_contracts.py
  • tests/unit/storage/test_archive_tiers_assertions.py
  • tests/unit/storage/test_archive_tiers_search_guard.py
  • tests/unit/storage/test_delegations_view.py
  • tests/unit/storage/test_fts5.py
  • tests/unit/storage/test_hybrid.py
  • tests/unit/storage/test_hybrid_laws.py
  • tests/unit/storage/test_query_mappers.py
  • tests/unit/storage/test_repair.py
  • tests/unit/storage/test_retrieval_readiness_laws.py
  • tests/unit/storage/test_schema_policy_contracts.py
  • tests/unit/storage/test_search_explanation_wiring.py
  • tests/unit/storage/test_session_insight_status_descriptors.py
  • tests/unit/storage/test_session_topology.py
  • tests/unit/storage/test_store_ops.py
  • tests/unit/storage/test_vec.py
  • tests/unit/surfaces/test_message_render_envelope.py
  • tests/unit/surfaces/test_search_cursor_pagination.py
  • tests/unit/surfaces/test_search_envelope_contract.py
  • tests/unit/surfaces/test_search_explanation_contract.py
  • tests/unit/test_protocol_conformance.py
  • tests/unit/test_read_surface_coherence.py
  • tests/unit/test_session_profile_staleness_predicate.py
  • tests/unit/test_sqlite_connection_hygiene.py
  • tests/unit/verification/test_code_refs_resolve.py

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/refactor/sqlite-leak-sweep-and-staleness-unify

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: fcf1497fbd

ℹ️ 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".

Sinity added 14 commits July 14, 2026 17:51
… leaks

Problem: `with sqlite3.connect(...) as conn:` commits/rolls back on exit but
never closes the connection — the well-known sqlite3 context-manager trap
already fixed once in insights/otlp_correlation.py. The previously-named hot
paths (coordination/envelope.py, api/user_state_resolver.py, api/archive.py,
storage/repair.py, demo/seed.py) were already remediated by prior work, but a
repo-wide sweep found 44 remaining bare-connect sites across daemon, cli,
sources, and storage — several on daemon hot/poll paths (daemon/http.py,
sources/live/watcher.py, storage/blob_gc.py, storage/repair.py).

What changed: wrapped every remaining bare `with sqlite3.connect(...)` in
`contextlib.closing()` (or the module's existing `from contextlib import
closing` alias) across 18 files, so the connection is explicitly closed on
exit rather than left to refcounting/GC. Added
tests/unit/test_sqlite_connection_hygiene.py: runtime connection-capture tests
on 5 representative helpers across daemon/cli/storage (assert the connection
raises ProgrammingError after the helper returns) plus a parametrized static
check that the swept modules no longer contain the bare pattern textually.
Verified anti-vacuity by reverting one site and confirming both tests fail.

Ref polylogue-a7xr.1.
Problem: daemon/convergence_stages.py and storage/repair.py (plus a third
copy in storage/insights/session/status.py's repair-candidate and
readiness-count queries) each independently encoded the staleness check for
session_profiles/session_latency_profiles rows. They agreed on the common
case (sort_key_ms IS NOT NULL: compare source_sort_key within a 1e-6
epsilon) but diverged for NULL-sort_key_ms sessions ("timeless" sessions
with no derivable temporal sort key): the converger compared the profile's
source_updated_at against the session's updated_at_ms, while repair and
status.py instead COALESCEd the missing sort key to 0.0 and compared it
against source_sort_key — permanently flagging any NULL-sort_key_ms session
with a nonzero cached source_sort_key as stale regardless of the converger's
verdict. That produced either indefinite repair churn or missed rebuilds
depending on which path ran first.

What changed: extracted the converger's (better-considered) predicate into
session_profile_stale_predicate(sessions_alias, profile_alias) in
storage/insights/session/runtime.py, and rewired all 6 call sites (3 in
convergence_stages.py, byte-identical SQL; 2 in repair.py's
_targeted_session_insight_rebuild_ids profile/latency UNION arms; 3 in
status.py's SESSION_PROFILE_REPAIR_CANDIDATES_SQL,
STALE_SESSION_PROFILE_COUNT_SQL, STALE_SESSION_LATENCY_PROFILE_COUNT_SQL) to
compose from it. repair.py's and status.py's semantics genuinely change for
NULL-sort_key_ms sessions to match the converger.

Added tests/unit/test_session_profile_staleness_predicate.py: a fixture with
sort_key_ms NULL + nonzero source_sort_key is classified identically ("fresh"
when source_updated_at agrees, "stale" when it doesn't) by the real
convergence pass (convergence_stages._stale_session_profile_ids) and the real
ops-repair pass (repair._targeted_session_insight_rebuild_ids), plus an
idempotence test (repair selects zero rows immediately after convergence
agrees) and a static single-definition check. Updated two pre-existing
test_repair.py fixtures and one test_session_insight_status_descriptors.py
fixture that were missing the source_updated_at/updated_at_ms columns the
unified predicate now references (they previously exercised the old
predicate's narrower column set). Verified anti-vacuity by reverting the
repair.py predicate to its buggy inline form and confirming 3 of the 4 new
tests fail.

Ref polylogue-a7xr.2.
Problem: OperationSpec.code_refs (operations/specs.py) and
ArtifactNode.code_refs (artifacts/runtime.py) are dotted-path strings no
runtime or test ever import-resolved — existing guards only checked
non-emptiness (test_specs.py) or regex shape (test_daemon_http_contracts.py),
or cross-checked one MCP tool slice by last path segment
(test_per_tool_contracts.py). A rename/move of a referenced symbol silently
strands the catalog ref, decaying the verification catalog's source
attribution invisibly.

What changed: added tests/unit/verification/test_code_refs_resolve.py, a
parametrized test that import-resolves every non-empty code_ref across
RUNTIME_OPERATION_SPECS, DECLARED_CONTROL_PLANE_OPERATION_SPECS, and
RUNTIME_ARTIFACT_NODES (202 refs) via importlib + getattr, with two
principled fallbacks for real-but-unusual symbol shapes: pydantic model
fields with no default (not set as class attributes in pydantic v2 — checked
via model_fields) and MCP tools defined as closures inside register_*
factories (unreachable via getattr by design — checked via a textual def-scan
of the owning module, which still catches a rename).

Running the resolver against the current catalog surfaced 9 already-stale
refs (not introduced by this change): polylogue.cli.commands.schema (module
never existed — CLI schema query has no dedicated command module),
polylogue.demo.seed_archive/verify_archive (renamed to seed.py/verify.py),
polylogue.api.archive.PolylogueArchive (renamed to PolylogueArchiveMixin),
polylogue.storage.repository.archive.repository_writes.RepositoryWritesMixin
(wrong class/module — save_artifact_observation lives on
storage.repository.raw.repository_raw.RepositoryRawMixin), and
SessionDigest.resume_bundle (no such field — the real symbol is the
render_resume_bundle function). Corrected all 9 to their real current
targets in both catalogs. Verified anti-vacuity by introducing a typo'd ref
and confirming the test fails naming the exact spec.

Ref polylogue-a7xr.17.
…port models

Problem: operations/operation_contract.py (277 LOC) defined a generic
OperationRequest/OperationAck subclassing framework meant to serve every
future mutating operation, but only OperationKind.IMPORT ever landed on it —
9 of 10 OperationKind enum members have zero production uses and nothing
dispatches on .kind. ImportAck existed solely to re-wrap the generic ack
pinning kind=IMPORT ("future import-specific fields land here" —
speculative generality), and _require_operation_kind guarded subclasses
that don't exist in production.

What changed: collapsed OperationRequest/OperationAck and
_require_operation_kind out of operation_contract.py, which now holds only
the genuinely reusable pieces — OperationStatus (every member has a real
consumer: readiness/capability.py maps RUNNING/COMPLETED/FAILED to
capability states) and OperationFollowUp (a plain data shape, not a
polymorphic base). import_operations.py's ImportRequest/ImportAck are now
concrete SurfacePayloadModel subclasses with their own fields instead of
inheriting the removed generics; ImportRequest keeps operation_kind as a
ClassVar (not a pydantic field) to preserve its prior wire shape exactly
(daemon HTTP echoes request.to_dict() in the ingest response body).
operations/__init__.py drops the removed OperationRequest/OperationAck
exports. specs.py's OperationKind enum is untouched (feeds the artifact/
operation catalog independent of this scheduling-contract collapse).

Wire stability: ImportAck.to_dict()'s JSON shape (the daemon HTTP
POST /api/ingest response envelope) and ImportRequest.to_dict()'s shape
(echoed in that same response as "request") are both byte-identical to
before — pinned by golden-payload tests in test_operation_contract.py
(TestImportAckSerialization, TestImportRequestValidation.
test_to_dict_roundtrip). Removed TestRequireOperationKind (tested the
now-deleted enforcement mechanism against synthetic non-production
subclasses) and folded its useful generic-OperationAck golden-JSON coverage
into ImportAck-specific tests, since ImportAck now owns the wire contract
directly.

Ref polylogue-a7xr.14.
devtools verify's dmypy step flagged tests/unit/test_sqlite_connection_hygiene.py's
_tracking_connect for implicitly returning Any (sqlite3.connect's overloads
don't resolve through a *args/**kwargs forward, so the bare `conn = ...`
assignment inferred Any). Annotate the local explicitly as sqlite3.Connection.

Ref polylogue-a7xr.1.
Problem: api/contracts/ write-surface protocols (IngestSurface,
MaintenanceSurface, TagMutationSurface, SessionDeleteSurface, WriteSurface)
and their adapters (CLIWriteSurface, APIWriteSurface, MCPWriteSurface) had
zero consumers outside the package itself — only their own contract test
(tests/unit/api/test_write_surface_contracts.py) constructed them. Worse,
the adapters were hand-written mirrors of the real CLI/MCP/API handlers
that had already diverged from the real execution paths:
CLIWriteSurface.ingest_path unconditionally returned a synthetic
status="failed" envelope instead of the real stage-and-POST-to-daemon flow
("the in-process projection ... requires a running daemon"), and
tag/delete conformance passed on method presence rather than execution
(the adapter's own docstring notes conformance still passes even when a
caller omits the facade dependency the mutation methods require). So the
parity guarantee assert_implements provided attached to a shadow object
free to drift from the surfaces it claimed to describe — the exact drift
class (#859) the layer was built to catch.

What changed: deleted write_surface.py (protocols), cli_write_surface.py,
mcp_write_surface.py, api_write_surface.py, and their self-referential
test file. api/contracts/__init__.py no longer imports/exports the
write-surface family; a docstring note records the removal + why, and
what re-anchoring assert_implements on the real handlers would look like
if write-surface parity enforcement is wanted again. Regenerated the
topology projection (devtools render topology-projection +
topology-status) to drop the four deleted modules.

Explicitly out of scope: api/contracts/read_surface.py and tui_surface.py
are untouched — TUIReadSurface is still a genuine consumer of
read_surface.py today (polylogue-f94, "kill the TUI", is decided but not
yet executed and is not part of this cluster); read_surface.py's own
unrelated dead TagMutationSurface duplicate is left for f94's sweep per
that bead's own coordination note.

Verification: devtools verify --quick green (ruff format/check, dmypy
--strict over the whole polylogue/ tree — 937 files, render all --check
with no "out of sync" surfaces); devtools test over
tests/unit/api/test_read_surface_contracts.py,
tests/unit/core/test_artifact_specs.py, tests/unit/core/test_artifact_graph.py,
tests/unit/devtools/test_artifact_graph.py, tests/unit/test_protocol_conformance.py,
tests/unit/test_read_surface_coherence.py — 82 passed. rg confirms zero
remaining references to the deleted classes/protocols outside this diff's
own docstrings.

Ref polylogue-a7xr.13.
Problem: FTS5Provider and HybridSearchProvider (storage/search_providers/)
had zero production call sites — verified live: production lexical search
queries FTS5 tables directly, and hybrid retrieval fuses FTS+vector results
inline against live query-plan state in two places (cli/archive_query.py,
archive/query/archive_execution.py; a third, archive/query/retrieval_search.py,
imports reciprocal_rank_fusion the same way). The classes and their
create_hybrid_provider/create_search_provider factories were exercised only
by their own tests (test_fts5.py, test_hybrid.py, test_hybrid_laws.py) and
test_protocol_conformance.py's isinstance checks — an unproven abstraction
with no consumer to keep it honest, per polylogue-a7xr.10's kill-or-adopt
framing.

Decision (owned here per the bead's "whoever executes first" rule — mhx.3
had not executed): KILL. Adoption would mean moving two independently
duplicated inline fusion implementations behind an interface neither has
been reconciled with yet (the archive_execution.py/hybrid_sessions.py
session-resolution dedup gap noted in mhx.3) — a materially larger, riskier
change than removing dead code, and not what this bead asked for.

What changed: deleted fts5.py (FTS5Provider), hybrid_factory.py
(create_hybrid_provider), and the SearchProvider protocol from protocols.py.
storage/search_providers/hybrid.py now holds only reciprocal_rank_fusion —
the one piece of this module production code actually imports directly, kept
per the bead's explicit instruction alongside hybrid_sessions.py's
session-resolution helpers (also kept: they're the target for the still-open
dedup fix, not dead weight) and the full SqliteVecProvider vector half
(create_vector_provider, 8 production call sites, untouched).
search_providers/__init__.py and protocols.py no longer export the removed
symbols. Deleted the three self-referential test files and trimmed
test_protocol_conformance.py's TestSearchProviderConformance (kept
TestVectorProviderConformance/TestConsoleLikeConformance/
TestParserModuleInterface, which cover the surviving protocols).

Housekeeping: updated docs/architecture.md's abstraction table, regenerated
the topology projection (2 fewer modules), and synced the three manifests
verify manifests / verify closure-matrix cross-check against the removed
files (docs/plans/campaign-coverage.yaml + devtools/mutation_scenario_catalog.py's
authored mutation-campaign catalog — removed the "fts5" campaign, repointed
"hybrid" at reciprocal_rank_fusion's real test coverage
(test_filters_props.py, test_query_search_runtime.py); docs/plans/
test-closure-matrix.yaml and test-coverage-domains.yaml similarly repointed).

Verification: devtools verify --quick green end to end (ruff format/check,
dmypy --strict over 935 files, render all --check with no "out of sync"
surfaces, verify topology/layering/closure-matrix/manifests all clean).
devtools test over tests/unit/test_protocol_conformance.py,
tests/unit/verification/test_code_refs_resolve.py,
tests/unit/core/test_filters_props.py,
tests/unit/storage/test_archive_search_contracts.py,
tests/unit/archive/test_query_search_runtime.py,
tests/unit/cli/test_archive_query.py,
tests/unit/devtools/test_mutation_catalog.py,
tests/unit/test_mutmut_campaign.py — 10 pre-existing failures in
test_archive_search_contracts.py/test_filters_props.py (unrelated origin/
provider-filter keyword drift) reproduce identically against the pre-change
tree (git stash verified); everything else passes.

Ref polylogue-a7xr.10.
Problem: polylogue-c9y's package-topology doctrine names four loose
top-level modules as folklore ("where does X go?" has no answer) and
specifically calls for core/ to absorb types.py/protocols.py/errors.py
so the top-level package surface shrinks toward zero non-entrypoint
modules.

What changed: polylogue/errors.py, polylogue/protocols.py, and
polylogue/types.py move to polylogue/core/{errors,protocols,types}.py
(git-tracked renames). All 165 import sites across polylogue/, tests/,
and devtools/ updated from `polylogue.errors`/`polylogue.protocols`/
`polylogue.types` to `polylogue.core.errors`/`polylogue.core.protocols`/
`polylogue.core.types` (absolute imports only — no relative-import call
sites existed for these three modules). No behavior change: pure
module relocation, symbol names and contents untouched.

Regenerated the topology projection (docs/plans/topology-target.yaml,
docs/topology-status.md) since this moves modules; the root polylogue/
package now has 7 non-package files (assets, config, __init__, logging,
__main__, services, version) instead of 10.

Verification: devtools verify --quick green (ruff format/check, dmypy
--strict, render all --check with no "out of sync" surfaces, topology/
layering/closure-matrix/manifests all clean). devtools test
tests/unit/core/ tests/unit/test_protocol_conformance.py -k "not slow"
ran 1597/2123 tests with zero failures before a shared-host timeout
killed the process (system under concurrent multi-agent load); mypy
--strict is the repo's stated primary net for type/identifier moves
of this shape and passed clean.

Ref polylogue-c9y.
Problem: polylogue/ has ~32 top-level subpackages and the boundaries
between several (archive/ vs storage/ vs operations/ vs maintenance/;
surfaces/ vs rendering/ vs ui/ vs cli/; the former loose types.py/
protocols.py/errors.py) were folklore — "where does new module X go?"
had no answer beyond asking someone who remembered a past PR
discussion. The topology-projection drift gate enforces the CURRENT
tree faithfully but has no opinion on whether the tree is well-shaped.
polylogue/analytics/ is coming (per the rxdo measurement-substrate
work landing this wave) with no stated rule distinguishing it from
insights/ — this needed deciding before, not after, the first PR adds
it.

What changed: replaced docs/architecture.md's stale "Placement Rules"
section (still referenced the removed lib/ package) with: (1) an
8-question decision procedure a newcomer/agent can apply directly
instead of pattern-matching on precedent, (2) six worked examples
covering the archive/storage/operations/maintenance boundary the
description called out as most confused, (3) the insights-vs-analytics
vocabulary rule (materialized read model vs. pure stateless
computation, with the composition direction fixed one way), (4) the
presentation-layer consolidation target (surfaces/rendering/ui/cli),
recorded as a direction to execute opportunistically rather than a
big-bang move, and (5) a stale protocols.py reference in the Key
Abstractions table fixed to core/protocols.py following the
polylogue-c9y core/ absorption move landed in the prior commit.

No topology-target.yaml/topology-status.md changes needed — this is a
docs-only addition, not a module move.

Verification: devtools render all --check green (grep for "out of
sync": none).

Ref polylogue-c9y.
Problem: archive/write_effects.py's commit_archive_write_effects is the
one canonical choke point every archive write path routes through, but
its effect list was hard-coded inline branches. Each new derived
product (embedding scheduling, SSE announce, daemon cache
invalidation, future webhooks) would mean editing the choke point and
re-reasoning its ordering/transaction-boundary/failure-isolation
properties by hand from the function body — a merge hotspot and
ordering hazard as those consumers land (polylogue-yp0's bus
subscribers land on the post-commit/async-deferred phases this slice
declares).

What changed (slice 1 of 2 per the bead's own contract-first split —
slice 2 is phase-enforcement/scheduling for async-deferred effects,
tracked as it lands with a real consumer): a WriteEffect
dataclass (name, phase: in-transaction | post-commit | async-deferred,
should_run predicate, failure_policy: abort | log-and-continue) and an
ordered WRITE_EFFECT_REGISTRY tuple. commit_archive_write_effects now
walks the registry generically instead of inlining
ensure_fts_triggers_sync/repair_message_fts_index_sync/
invalidate_search_cache — those three become the registry's first three
entries, behavior-identical (same conditions: FTS repair only runs
when changed_session_ids is non-empty and repair_message_fts isn't
explicitly False; cache invalidation only when session ids changed;
commit sits between the in-transaction and post-commit phases exactly
as before). The phase distinction makes the next effect's placement a
declared decision instead of archaeology, and per-effect failure_policy
kills a real bug class the module already carried an example of (the
now-removed blob-lease branch could poison unrelated effects on
failure — documented in the new WRITE_EFFECT_REGISTRY docstring instead
of left implicit).

No behavior change to the log line semantics that matter (slow-path
threshold, operation/session-count fields); the per-effect timing
breakdown is now built from the effects that actually ran rather than
three always-present fixed fields, which is strictly more accurate
under a skip.

Verification: devtools test tests/unit/archive/test_write_effects.py
tests/unit/archive/test_write_gateway.py — 12 passed (new registry
shape/order test, seeded positive case exercising both in-transaction
and post-commit effects, a degraded/empty case with no changed session
ids exercising should_run skip paths, an explicit repair_message_fts
opt-out, and both failure_policy branches — abort propagates,
log-and-continue does not poison a later effect). mypy --strict clean
on both files. devtools verify --quick green (ruff/mypy/render/
topology/layering/closure-matrix/manifests all pass).

Anti-vacuity: test_abort_failure_policy_propagates exercises a real
production dependency (WRITE_EFFECT_REGISTRY as read by
commit_archive_write_effects's own _run_registered_effects walker, not
a test-local reimplementation) — replacing the walker's `raise` with a
swallow, or removing the `if effect.phase != phase or not
effect.should_run(ctx): continue` phase/should_run gate, makes
test_commit_write_effects_degraded_case_skips_conditional_effects_when_no_ids
and test_repair_message_fts_should_run_honors_explicit_opt_out fail
(they assert zero calls into monkeypatched
fts_lifecycle.repair_message_fts_index_sync/
search.cache.invalidate_search_cache when should_run is false).

Separately confirmed pre-existing, unrelated to this change:
tests/unit/pipeline/test_ingest_batch.py::
test_process_ingest_batch_sync_reserves_inline_attachment_until_index_commit
(both parametrizations) fails with the ORIGINAL, un-refactored
write_effects.py in the working tree (reproduced by temporarily
reverting this file) — a stale blob_publication_reservations row
survives a batch that the test expects fully drained; not filed as a
new bead in this PR since Ref polylogue-a7xr.1's sqlite-connection-leak
sweep and blob-lease code paths are directly upstream and already
tracked, but flagged here for the operator to triage rather than
silently absorbed as "tests pass".

Ref polylogue-0aj.
…ue-1r9c)

Problem: polylogue-1r9c asks for a source-grounded hotspot map of
Polylogue's largest execution control centers plus at least one
coherent extraction slice that makes a named control center materially
smaller with no duplicate execution path, filing the rest as durable
child beads.

What changed:

1. docs/architecture-hotspots.md — new hotspot map covering all eight
   named control centers (storage read tier 11.3k lines, API facade
   5.9k, storage repair 5.6k, daemon HTTP 4.6k, storage write tier
   4.6k, CLI query dispatch's _execute_archive_query_stdout 632-line
   function, daemon service loop's run_daemon_services 475-line
   function, MCP register_read_tools/register_mutation_tools) with
   file:line evidence, call-boundary/ownership-seam analysis, and a
   prioritized extraction sequence. Documents why this slice targeted
   the write tier rather than the two larger hotspots (storage repair's
   three internal blocks share an untraced pool of generic helpers and
   one dataclass whose declaration/usage location is already
   mismatched — building that dependency graph is real, separate work;
   the read tier has the widest fan-in in the codebase and needs a
   broader regression net than one pass's budget covers).

2. polylogue/storage/sqlite/archive_tiers/session_annotations_write.py
   (new) — the ArchiveSessionTag/ArchiveSessionWorkEvent/
   ArchiveSessionPhase dataclasses and their upsert_session_tag/
   read_session_tags/upsert_session_work_event/read_session_work_events/
   upsert_session_phase/read_session_phases functions, moved verbatim
   from write.py, plus the four small helpers only they use. This block
   had zero callers into or from write_parsed_session_to_archive or any
   other write.py function — confirmed by dependency tracing before
   moving anything, matching the AC's "no duplicate execution path"
   requirement. The one shared dependency (_json_dumps, used by 8 other
   write.py call sites so it correctly stays there) is imported back
   lazily inside the moved functions' bodies to avoid a module-init-time
   circular import — the same lazy-import pattern write.py's own
   _mirror_session_tag_assertion_if_available already used for its
   user_write.py dependency.

3. write.py re-exports all nine public names unchanged (same import
   path for every external caller: archive_tiers/archive.py and the
   test suite import ArchiveSessionPhase/ArchiveSessionWorkEvent from
   polylogue.storage.sqlite.archive_tiers.write exactly as before).
   write.py: 4,595 -> 4,210 lines (-385, -8.4%).

4. docs/plans/layering.yaml — the writer-module layering policy tracks
   which physical file owns which mutating entrypoint per tier by
   parsing each file's "Writer module: <tiers>." docstring marker
   against a manifest. Moved the session-tag-assertion-mirror twin-write
   contract's module reference and the three relocated entrypoints from
   write.py's manifest entry to a new session_annotations_write.py
   entry; write.py's own declared tiers narrow from [index, user] to
   [index] since none of its remaining entrypoints touch the user tier
   directly (verified via the checker's own _mutation_tiers analysis).
   This surfaced a separate, pre-existing imprecision in
   archive_tiers/archive.py's "raw-revision-authority" twin-write
   contract: the checker's transitive tier attribution is coarse
   (crediting a WHOLE imported module's declared surface for any call
   into it, not the specific called function's real footprint), so
   archive.py's claimed "user" tier reach was riding entirely on that
   coarseness through its write.py import — with write.py's declared
   surface correctly narrowed, static tracing of all 11 of archive.py's
   declared entrypoints confirms none of them touch the user tier
   through any traceable path. Corrected archive.py's docstring/manifest
   to [index, source] (dropping the never-actually-proven "user" claim)
   and replaced the raw-revision-authority contract with a
   raw-membership-classification contract whose surfaces match reality
   ([index, source], proven by apply_raw_membership_classification's
   traced footprint) — a documentation/proof-declaration correction with
   no runtime behavior change, not a new claim about what the code does.

5. devtools/docs_surface.py + docs/README.md + CLAUDE.md — index the
   new architecture-hotspots.md doc (the docs-surface render gate
   rejects unindexed documentation files) and add it to CLAUDE.md's
   reference-docs table.

6. Filed six child beads for the remaining seven control centers per
   AC-5 (each with an explicit non-goal so it can't balloon into a
   second decompose-everything mega-bead): polylogue-redt (storage read
   tier — build the helper-dependency graph first), polylogue-u5dw
   (storage repair — resolve the three blocks' shared-helper coupling +
   the c9y storage-vs-maintenance placement question), polylogue-1vzf
   (CLI query dispatch — registry-ize the output-format branches,
   following this bead's own write-effects-registry precedent),
   polylogue-gikp (API facade — investigate verb-group mixins),
   polylogue-kchb (daemon HTTP — extend the existing web_shell_*.py
   satellite pattern), polylogue-avmq (daemon service loop — blocked-by
   polylogue-yp0 since the event-bus work will reshape this function's
   body directly), polylogue-w9di (MCP tool registration — lowest
   priority, already has a delegation pattern in place).

Verification: mypy --strict clean on write.py + session_annotations_write.py
+ archive.py. ruff check clean. devtools verify --quick green end to
end (ruff/mypy/render/topology/layering/closure-matrix/manifests all
pass — layering specifically required the archive.py contract fix
above to go green, verified via a standalone script replicating the
checker's own _entrypoint_tiers/_mutation_tiers functions before and
after). devtools test tests/unit/storage/test_archive_tiers_write.py
tests/unit/storage/test_archive_tiers_self_verify.py (64 passed) and
tests/unit/storage/test_revision_replay.py (16 passed, covers
apply_raw_membership_classification specifically) — full behavioral
parity, zero regressions. devtools render all --check green (no "out
of sync"/"unindexed" findings).

Ref polylogue-1r9c.
Problem: the daemon runs ~9 concurrent maintenance loops (mapped by
polylogue-9e5.7's lock/starvation audit) coordinating today through
polling and shared tables — convergence checks for debt, embedding
catch-up polls pending counts, FTS status re-derives, alerts re-scan.
Each new daemon feature has meant another loop with its own cadence,
its own DB polling, and its own interaction-risk surface against the
daemon's single-writer invariant.

What changed: polylogue/daemon/event_bus.py — a small typed in-process
pub/sub bus (no broker, no cross-process delivery, matching the design
note's explicit non-goal that cross-process eventing is Sinex
territory). Five frozen dataclass events matching the design's
vocabulary (IngestCommitted, CursorMoved, ConvergenceStateChanged,
EmbeddingPending, BlobLeaseReleased); EventBus.subscribe/publish/
unsubscribe with the failure-isolation contract the design calls for
explicitly: a raising subscriber is logged and does not prevent
delivery to its siblings on the same publish, and does not get
silently dropped from future publishes (a subscriber that always
raises still gets called every time — "a crashed subscriber must not
silently stop forever").

Status — honest partial, not a full close: this lands the bus core
with complete unit coverage (10 tests: multi-subscriber fan-out, empty
delivery, type-scoped delivery, both failure-isolation properties,
unsubscribe including idempotence, subscriber-count bookkeeping, and a
frozen-dataclass immutability pin for all five event types) but does
NOT yet wire it into any live daemon producer or consumer. The design
note itself sequences this deliberately ("Sequence: after 9e5.7
produces the loop inventory, convert with the map in hand") — actually
converting a live polling loop to subscribe touches the same
lock/starvation-sensitive daemon machinery 9e5.7 spent a dedicated
investigation mapping, and forcing that integration under this pass's
time budget risked exactly the kind of hasty daemon-internals change
this repo's CLAUDE.md warns against. Filed polylogue-14t7
(blocked-by polylogue-yp0) for the actual producer wiring (a new
async-deferred WriteEffect entry in the polylogue-0aj registry
publishing IngestCommitted) and one real consumer conversion (embedding
catch-up waking on EmbeddingPending, the design note's suggested first
candidate) — the acceptance test's "ergonomics payoff" ("adding a new
daemon behavior = one subscriber function") is unprovable without that
follow-up landing, so this commit does not claim it.

Verification: mypy --strict clean (had to rewrite the initial draft off
PEP 695 generic syntax — type X[T] / def f[T] — since this repo targets
Python 3.11, not 3.12; classic TypeVar instead). ruff check clean.
devtools test tests/unit/daemon/test_event_bus.py — 10/10 passed.
devtools verify --quick green end to end (ruff/mypy/render/topology/
layering/closure-matrix/manifests). devtools render topology-projection
&& topology-status regenerated for the new module.

Ref polylogue-yp0.
Problem: rebasing feature/refactor/sqlite-leak-sweep-and-staleness-unify
onto origin/master (which gained #2875/#2876/#2877 since this branch was
cut) produced conflicts in the generated topology-target.yaml and
topology-status.md artifacts. Both sides had regenerated these
independently from source, so a manual merge would desync them from the
actual module graph.

What changed: resolved the conflicts with a placeholder (--ours), then
ran `devtools render topology-projection && devtools render
topology-status` to regenerate both files from the post-rebase source
tree, matching this repo's documented policy for generated-surface
conflicts.

Verification: `devtools render all --check` reports no "out of sync"
lines (all surfaces sync OK).
Problem: adversarial review of PR #2900 found (1) a new pre-existing test
failure discovered while re-running the write-tier suite post-rebase
(test_fresh_user_tier_has_no_legacy_overlay_tables asserts an exact table
set that migrations 007/008, both merged well before this branch was cut,
already invalidated), and (2) polylogue-a7xr.10's own acceptance criteria
("if kill: ... mhx.3 notes it owns lane construction") was not yet
satisfied after the FTS5Provider/HybridSearchProvider kill decision landed.

What changed: filed polylogue-ihp0 for the stale-table-set test assertion
(confirmed pre-existing via `git merge-base --is-ancestor`: the migration
commit predates this branch's own base). Appended a note to polylogue-mhx.3
recording that it now owns lane construction/comparison for the
FTS-vs-vector-vs-hybrid eval, since the shared SearchProvider abstraction
a7xr.10 killed no longer exists to build the eval harness against.

Note: `bd export`/the beads pre-commit hook resolve their write target
from bd's own database location, independent of invoking cwd, so running
`bd create`/`bd update` from this worktree wrote its export to the MAIN
checkout's .beads/issues.jsonl (on an unrelated branch) rather than this
worktree's file. Reverted that accidental main-checkout write and instead
hand-applied both deltas directly to this worktree's .beads/issues.jsonl,
verifying every line still parses as JSON, per this repo's documented
mitigation for the bd-export cwd-independence gotcha.

Ref polylogue-1r9c, polylogue-a7xr.10.
@Sinity
Sinity force-pushed the feature/refactor/sqlite-leak-sweep-and-staleness-unify branch from fcf1497 to bfb6415 Compare July 14, 2026 16:05
… refs

Problem: two round-2-review findings on this branch were left unfixed from
a prior automated-review pass.

1. a7xr.1's sqlite-leak sweep changed the pending-attachment-receipt
   connection in _process_ingest_batch_sync from `with sqlite3.connect(...)
   as conn:` (which both commits and closes) to `with closing(sqlite3.
   connect(...)) as conn:` (contextlib.closing only closes). The block
   BEGINs a transaction and calls consume_blob_publication_receipt (itself
   uncommitted); on the bare close(), sqlite3 rolled the transaction back,
   so every consumed blob-publication-reservation row silently survived.
   Reproduced live: devtools test tests/unit/pipeline/test_ingest_batch.py
   -k reserves_inline_attachment failed 2/2 (assert 1 == 0) before this fix,
   passes after. Reverting the fix reproduces the exact failure, confirming
   the mutation is load-bearing.

2. a7xr.10 killed polylogue/storage/search_providers/fts5.py (FTS5Provider)
   but devtools/storage_correctness_scenario.py and devtools/
   synthetic_benchmark_runtime.py still imported it, crashing `devtools lab
   smoke list`/`smoke run storage-correctness` and the incremental-index
   benchmark campaign with ModuleNotFoundError.

Solution:
- _core.py: nest the sqlite3.Connection's own context manager inside
  closing() (`with closing(...) as conn, conn:`) so the block both commits
  on success / rolls back on exception AND closes on exit. Matches ruff
  SIM117's single-with suggestion.
- storage_correctness_scenario.py: replace FTS5Provider(...).search() with
  the surviving production search surface, polylogue.storage.search.
  search_messages(archive_root=, db_path=), which raises the same
  DatabaseError on missing FTS triggers and exposes .hits for the
  post-repair assertion.
- synthetic_benchmark_runtime.py: replace FTS5Provider(...).index() with
  the exact primitives it wrapped internally (ensure_index +
  replace_fts_rows_for_messages_sync + invalidate_search_cache), converting
  messages to (message_id, session_id, text) tuples as the killed class did
  — avoids a mypy --strict Protocol-invariance mismatch between
  MessageRecord's NewType fields and IndexedMessage's plain str fields.

Verification:
- devtools test tests/unit/pipeline/test_ingest_batch.py -k
  reserves_inline_attachment -> 2 passed (was 2 failed on HEAD).
- python3 -m devtools lab smoke list / smoke run storage-correctness ->
  both run clean (previously ModuleNotFoundError on smoke list).
- devtools test tests/unit/pipeline/test_ingest_batch.py tests/unit/
  devtools/test_benchmark_campaigns.py -> 62 passed.
- devtools verify --quick -> exit_code 0 (ruff format/check, mypy --strict,
  render all --check, topology/layering/closure-matrix/manifests all
  clean).
- Anti-vacuity: built a real synthetic archive via devtools.
  large_archive_generator.generate_archive, manually emptied the real
  index.db's messages_fts (2534 rows), ran run_incremental_index_campaign
  against the resolved index.db path, confirmed all 2534 rows were
  repopulated via replace_fts_rows_for_messages_sync (the exact FTS5Provider
  .index() internals) -- proves the replacement is behaviorally faithful,
  not just import-clean.

Discovered but out of scope: run_full_campaign/run_synthetic_benchmark_
campaign pass db_path=archive_dir/"benchmark.db" straight into open_
connection()/connection_context(), but SQLiteBackend(db_path=X).db_path
always resolves to X.parent/"index.db" regardless of filename -- every
synthetic benchmark campaign that opens its own connection (fts-rebuild,
incremental-index) has always written to a phantom "benchmark.db" file
next to the real index.db, not the archive the campaign reports metrics
against. Predates a7xr.10 (the pre-removal FTS5Provider-backed campaign
had the identical bug) and spans multiple campaigns beyond this PR's
scope. Filed polylogue-ovme.

Ref polylogue-1r9c, polylogue-a7xr.1, polylogue-a7xr.10.

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

Sinity commented Jul 14, 2026

Copy link
Copy Markdown
Owner Author

Fix round: addressed both blocker findings from the round-2 automated review (commit dc18e87).

Blocker 1 (polylogue-a7xr.1, silently-broken blob-receipt commit): _process_ingest_batch_sync's pending-attachment-receipt block used with closing(sqlite3.connect(...)) as conn: — closing() only calls .close(), it does not commit, so the BEGIN IMMEDIATE transaction consuming blob-publication receipts silently rolled back on every commit. Fixed by nesting the connection's own commit/rollback context manager inside closing(): with closing(sqlite3.connect(...)) as conn, conn:. Confirmed the mutation is load-bearing: reverted the one-line fix locally and reproduced the exact reported failure (tests/unit/pipeline/test_ingest_batch.py -k reserves_inline_attachment — 2 failed, assert 1 == 0); restored the fix and both pass.

Blocker 2 (polylogue-a7xr.10, stale FTS5Provider references): devtools/storage_correctness_scenario.py and devtools/synthetic_benchmark_runtime.py still imported the deleted FTS5Provider, breaking devtools lab smoke list/smoke run storage-correctness and the incremental-index benchmark campaign with ModuleNotFoundError. Replaced with the surviving production surfaces: storage_correctness_scenario.py now calls polylogue.storage.search.search_messages(...) (same DatabaseError-on-missing-trigger behavior, .hits for the post-repair count); synthetic_benchmark_runtime.py now calls the exact primitives FTS5Provider.index() used internally (ensure_index + replace_fts_rows_for_messages_sync + invalidate_search_cache), converting messages to (message_id, session_id, text) tuples the same way the deleted class did (needed to satisfy mypy --strict's Protocol-invariance check against MessageRecord's NewType fields).

Anti-vacuity check on blocker 2: built a real synthetic archive via devtools.large_archive_generator.generate_archive, manually emptied the real index.db's messages_fts (2534 rows), ran run_incremental_index_campaign against the resolved index.db path, and confirmed all 2534 rows were repopulated — proves the replacement is behaviorally correct, not just import-clean.

Discovered but explicitly out of scope, filed as polylogue-ovme: run_full_campaign/run_synthetic_benchmark_campaign pass db_path=archive_dir/"benchmark.db" straight into open_connection()/connection_context(), but SQLiteBackend(db_path=X).db_path always resolves to X.parent/"index.db" regardless of the filename passed in — every synthetic benchmark campaign that opens its own connection (fts-rebuild, incremental-index) has always written to a phantom benchmark.db file next to the real index.db, not the archive the campaign reports metrics against. This predates a7xr.10 (the FTS5Provider-backed campaign had the identical bug) and spans multiple campaigns — a materially larger fix than this round's scope.

Verification:

  • devtools test tests/unit/pipeline/test_ingest_batch.py tests/unit/devtools/test_benchmark_campaigns.py — 62 passed
  • python3 -m devtools lab smoke list / smoke run storage-correctness — both clean (previously ModuleNotFoundError)
  • devtools verify --quick — exit 0 (15/15 steps, ruff format/check, mypy --strict, render all --check, topology/layering/closure-matrix/manifests)
  • Pre-push quick verification baseline also green on push.

Ref polylogue-1r9c, polylogue-a7xr.1, polylogue-a7xr.10.

# Conflicts:
#	docs/plans/topology-target.yaml
#	docs/topology-status.md
#	polylogue/api/archive.py
#	polylogue/archive/session/neighbor_candidates.py
#	polylogue/cli/commands/maintenance.py
#	polylogue/storage/sqlite/archive_tiers/write.py
@Sinity
Sinity merged commit d068d64 into master Jul 14, 2026
1 of 2 checks passed
@Sinity
Sinity deleted the feature/refactor/sqlite-leak-sweep-and-staleness-unify branch July 14, 2026 18:27
Sinity added a commit that referenced this pull request Jul 15, 2026
…erifying

## Problem

polylogue-a7xr.9 flagged 36 duplicate `_table_exists` implementations
scattered across the codebase, all supposedly superseded by a canonical
`table_exists()`/`table_exists_async()` pair. That canonical pair had never
been tested and was broken: it bound `db` as a query parameter against
`sqlite_master`, which has no `db` column, so every call raised
`sqlite3.OperationalError`.

Verifying the fix (`devtools verify`) exposed two batches of pre-existing,
unrelated test failures that a full-suite run surfaces but the narrower
testmon-affected selection normally used in this repo hadn't caught:
27 failures from stale test fixtures/assertions trailing recent feature
landings, and a further 50 only visible once testmon fell back to a
near-full-suite selection. All were confirmed pre-existing via `git stash`
comparison against clean `origin/master` before being touched.

## Solution

**Canonical table-existence helper** (polylogue-a7xr.9): fixed the
`AND db=?` bug (dynamic schema-name interpolation instead, matching the two
call sites that already did this correctly), wrote real tests against actual
SQLite connections (including the attached-schema path), and placed the
module at `storage/table_existence.py` -- directly under `storage/`, not
nested under `storage/sqlite/`. This satisfies two constraints that first
looked incompatible: `docs/architecture.md`'s package-placement rules
require raw SQL to live under `storage/` (ruled out `core/`, where an
earlier draft of this PR briefly placed it -- caught by CodeRabbit review),
while `polylogue/storage/sqlite/__init__.py` eagerly imports the heavy async
backend stack, so a low-level module like `storage/blob_publication.py`
importing a sibling under `storage.sqlite` triggers that whole chain and
circles back through `insights/` -- a real circular import. `storage/__init__.py`
itself only exposes lazy `__getattr__`-based exports, so a module living
directly under `storage/` avoids that chain entirely. Consolidated 26 sites
with identical `type='table'` semantics onto the canonical import (a 27th,
`session_insight_run_projection_reads.py`, fell out of scope entirely during
the rebase onto master: #2898 landed concurrently and dropped its
`_table_exists`-gated materialized-table check along with the run-projection
materialization feature it belonged to). Left 8 sites alone that use
genuinely different semantics (`type IN ('table','view')`,
`('table','virtual table')`, or `('table','shadow')`) and one
(`cli/commands/status.py`) that already delegates to its own generic
multi-type helper.

**Test/fixture drift sweep** (found while verifying, fixed rather than
dismissed as unrelated): stale `provider=`/bare-provider-token usages across
CLI, MCP, benchmark, and facade-contract tests that predate the
provider->origin vocabulary migration (including one place a fixture needed
the opposite direction -- `insights status`'s `provider_coverage` field
still legitimately reports provider tokens via `_provider_for_origin_value`,
which a first pass of this fix incorrectly "corrected" to an origin token;
caught by Codex review); a repeated `initialize_archive_tier()` double-init
bug across 4 test files (fixtures already get a fully initialized `user.db`
via `ArchiveStore(...)`/`cli_workspace`, so the extra call re-runs DDL
against existing triggers and crashes); a hardcoded `captured_at` timestamp
in `test_status.py` that goes stale with wall-clock time (now uses the
`frozen_clock` fixture, matching this repo's own convention); a missing
`EMBEDDINGS_SCHEMA_VERSION` constant reference (test hardcoded `1`, real
schema is now `2`); missing CLI short-flag aliases (`-l`/`-f`) on two
recently-added subcommands; 4 `AssertionKind` enum members
(`secret_candidate`, `excision_record`, `excision_request`,
`comparative_judgment`) missing their `user_audit.py` surface entries; 7 new
async `Polylogue` facade methods missing `status.py` route-catalog entries;
a new `include_affordances` MCP field missing from the query-descriptor
parity exclusion set; a new `semantic_cards` visual test missing its
inventory entry; 3 doc references to source paths that moved
(`storage/insights/topology/derivation.py`) or no longer exist as a single
file (`storage/search_providers/fts5.py` -> `storage/search/query_builders.py`
now builds the lexical FTS5 query); and a legitimate production behavior
change in `continue_verb` (#2827 removed context-compile/`--format json`
support in favor of safe-resume-command-only output) whose unit tests were
rewritten to assert the new rejection behavior instead of the removed one.

**Real production bug fixed, not just test drift**: `normalize_insight_query_kwargs`
(`polylogue/cli/shared/insight_command_contracts.py`) was popping `"origin"`
and renaming it to `"provider"`, downgrading origin tokens
(e.g. `"codex-session"`) to bare provider tokens (`"codex"`) via
`provider_from_origin`. Both call sites (`insights_status_command`,
`insights_export_command`) still read `filters["origin"]` afterward -- a
`KeyError` on every invocation with an origin filter -- while the underlying
`InsightReadinessQuery`/`InsightExportBundleRequest` models only accept
`origin` (confirmed via their own `Unknown query field(s)` error listing
accepted fields). Removed the origin->provider downgrade entirely; the CLI
layer now speaks the same origin vocabulary as the rest of the public
surface.

## Deferred (filed as tracked debt, not guess-fixed)

- polylogue-hjpx (P1): 7 raw-materialization repair tests fail --
  `backfill_historical_revision_evidence` classifies a candidate as
  replayable but never replays it. Traced far enough to rule out the most
  recent commit touching `repair.py` (#2900) as the cause; genuinely older
  debt that needs a dedicated tracing session, not a blind patch to a
  data-materialization repair path.
- polylogue-866e (P0): Hypothesis finds 3 distinct falsifying examples in
  `test_write_path_state_machine.py` -- real invariant violations in the
  session-lineage write path (fork/resume/prefix-replay composition), the
  sharpest and most fragile part of this architecture. Needs a focused
  investigation session.
- polylogue-j9dt (P1): `continue --format json` was fully removed by #2827,
  but two `QueryActionWorkflow` product-doc registry entries
  (`find-then-successor-context`, `find-then-continue`) still document it in
  detail. Needs a product decision, not a unilateral rewrite.
- polylogue-enj7 (P2): `test_daemon_cli_remote_bind.py`'s loopback-pass tests
  hang/error against real (unmocked) background raw-materialization
  convergence, confirmed on a freshly rebooted host. The module's own
  docstring already flags full-startup-chain mocking as "out of scope."
- polylogue-oucx (P2): 3 `test_facade_contracts.py` run/OTel query-unit
  tests fail deterministically, unrelated to this PR's diff (confirmed via
  `git diff origin/master` showing zero change to the relevant production
  files, and via reproducing identically on the pre-fix pushed branch
  content). Possibly a real gap left by #2898.

## Verification

- `devtools test tests/unit/storage/test_table_existence.py` -- 6/6 passed.
- Every touched test file run directly together, minus 3 confirmed-unrelated
  pre-existing failures in `test_facade_contracts.py` (polylogue-oucx) --
  768+ passed.
- Original 27-failure set and the fuller 50-failure set both re-run directly
  against this branch: 27/27 and 37/50 pass (the remaining 13 are the four
  items filed above, all independently confirmed pre-existing and
  unrelated via `git stash` comparison against clean `origin/master`).
- `mypy --strict polylogue` -- clean, 991 files.
- `ruff format --check .` / `ruff check .` -- clean.
- `devtools render all --check` -- clean, no drift, after two full module
  relocations (`storage/sqlite/table_existence.py` -> `core/` ->
  `storage/table_existence.py`) each re-verified for zero circular import
  (`python3 -c "import polylogue.storage.blob_publication"` exits 0).
- `devtools verify --quick` -- clean (ran automatically via pre-push hook).
- Addressed both substantive automated-review findings from CodeRabbit
  (package-boundary placement) and Codex (provider/origin fixture
  correctness) before merge, per repo review-triage discipline.

Ref polylogue-a7xr.9

Co-Authored-By: Claude <[email protected]>
Sinity added a commit that referenced this pull request Jul 27, 2026
## Summary

Executes polylogue-k7m7: independently re-verify and delete the
~30-symbol dead-code kill-list produced by polylogue-9e5.15's 2026-07-09
vulture+coverage+affordance-usage audit. Every symbol was re-checked
against the current tree (not blindly trusted from a ~2.5-week-old
audit) before deletion.

## Problem

polylogue-9e5.15 intersected three signals (vulture static analysis,
coverage.py 0%-function data, CLI/MCP affordance-usage telemetry) and
manually call-site-verified a ~30-symbol kill-list, documented in
`.agent/handoffs/polylogue-deep-research-2026-07-09/2026-07-09-codebase-structure-audit.md`
section 2. That audit was explicitly split into an audit half (closed)
and an execution half (this PR, polylogue-k7m7) because a lot can land
between finding dead code and deleting it.

## Solution

For every symbol on the list: fresh `rg` call-site search across
`polylogue/`, `tests/`, `docs/`; check for
test/CLI-registration/MCP-registration/generated-doc references; and for
one ambiguous case (a Protocol-declared method), a full-repo `mypy
--strict` run with the symbol removed to empirically confirm no
structural-typing consumer exists.

**Deleted (still genuinely dead):**
- `polylogue/cli/commands/agents.py`: `self_command`, `current_command`,
`conflicts_command`, `overlap_command`, `handoff_command` — 5 untested,
uncalled CLI subcommand wrappers. `agents status`/`agents work-item`
remain; the underlying `CoordinationView` substrate and MCP surface are
untouched, only these CLI aliasing wrappers are gone.
- `polylogue/archive/semantic/models.py`: `to_evidence_input` on all 6
semantic-facts dataclasses (zero call sites anywhere) + the now-unused
`JSONDocument`/`json_document` import.
- `polylogue/archive/query/plan.py`: 8 one-line `SessionQueryPlan`
wrapper methods (`_matches_referenced_path`, `_matches_action_terms`,
`_matches_tool_terms`, `_matches_action_sequence`,
`_matches_action_text_terms`, `_sort_generic`,
`_candidate_record_query_for`, `_search_limit`) that only forwarded to
free functions already called directly by their real callers, plus the
resulting unused imports (`candidate_record_query_for`, `search_limit`,
the `matches_*` family, `sort_generic`, `SortKey`).
- `polylogue/archive/query/expression.py`: `_merge_tuples`,
`_canonicalize_with_units`, `_source_where_unit` (zero callers) + the
unused `terminal_query_unit` import.
- `polylogue/archive/artifact_taxonomy/support.py`: `path_only_sidecars`
(one-line dict-returning wrapper, zero callers;
`path_only_sidecar_reason`, which reads the same dict directly, stays).
- `polylogue/storage/repository/archive/sessions.py`: `get_eager`.

**Skipped — found to have changed since the 2026-07-09 audit (not
deleted):**
- The 3 `cli/query_verbs.py` mark-candidate commands
(`reject`/`defer`/`supersede_mark_candidate_command`) **no longer exist
at all** — already deleted by PR #3138 (2026-07-19), which consolidated
the `mark candidates` subcommand group into the root `judge` command. No
action needed; this half of the audit's finding is stale in a "already
resolved" direction.
- The `polylogue/api/archive.py` half of the audit's "`get_eager` pair"
is also already gone — removed by the #2900 control-center
decomposition. Only the `storage/repository/archive/sessions.py` half
still existed and was deleted above.
- `get_eager` is now declared as a required method on two
`@runtime_checkable` Protocols (`SessionQueryRuntimeStore`,
`SessionOutputStore` in `polylogue/core/protocols.py`), added by PR
#2906 (2026-07-15, after the audit) when those protocols' methods were
inlined from a deleted shared base. This looked exactly like the "grew a
new reference since the audit" case the bead warned about, so I verified
it empirically rather than assuming either way: a full-repo `mypy
--strict` run with the concrete `sessions.py` method removed reports
zero errors, and grepping for `.get_eager(` call sites and
getattr/dynamic-dispatch patterns found none — the two Protocol
declarations themselves are never structurally checked against a real
`SessionRepository` instance anywhere in production code today. I
deleted the concrete method (documented above) but left the two Protocol
declarations untouched (out of this sweep's scope). This leaves the
Protocols describing a method their only real implementer no longer
provides — worth revisiting if `plan_execution.py`/`query_actions.py`
(themselves apparently production-unreferenced, test-only-exercised
query scaffolding using these exact Protocols) are ever wired into a
live call path.

## Verification

- `python -m mypy --strict polylogue` → `Success: no issues found in
1082 source files` (run after every deletion step, including a throwaway
pre-deletion probe specifically for the `get_eager` question).
- `ruff check polylogue` → `All checks passed!`; `ruff format --check
polylogue` → `1082 files already formatted`.
- `devtools test` against the ~40 test files that import the touched
modules: **11 failed, 291 passed**. Confirmed via `git stash` + re-run
against `origin/master` with the identical test-file set that all 11
failures are **pre-existing and unrelated** (same test names, same
assertion messages, same line numbers, with or without this diff).
- `devtools render all --check` → exit 0, no `out of sync` entries
(grepped per the repo's own gotcha about the tail line lying).
- `devtools verify --quick` (pre-push hook) → all 16 steps green (ruff
format/check, mypy, render all, topology, layering, closure-matrix,
schema roundtrip, manifests, ci-workflows, doc-commands, docs-coverage,
test-infra-currency, test-clock-hygiene, pytest-timeout-overrides,
degrade-loudly).

Ref polylogue-k7m7

---------

Co-authored-by: Claude <[email protected]>
Sinity added a commit that referenced this pull request Jul 27, 2026
…k bool env vars (#3340)

## Summary

Fresh `devtools verify --all` re-triage of polylogue-p6rz ("pre-existing
test
failures unrelated to MCP cutover") against current master. Fixes
several
confirmed real regressions and stale test assertions found during the
pass;
files properly-scoped follow-up beads for the rest instead of leaving
them as
anonymous re-discoveries.

## Problem

polylogue-p6rz's original list (from 2026-07-18) was stale: a lot has
merged
since. A fresh `devtools verify --all` run (107 failed, 14 errors on the
pre-fix baseline) needed re-triage to separate fixed / persisting /
newly
introduced failures, and specifically to catch any real regression from
this
session's merges (query DSL AST schema, browser-capture approval flow,
GitHub effect adapters, continuity replay wiring, etc.).

## Solution

**Confirmed real regressions, fixed:**

- `polylogue/config.py`: PR #3202's strict bool-env coercion rejected a
blank
  `POLYLOGUE_FORCE_PLAIN=""` value with `ConfigError` instead of the old
passthrough-as-falsy behavior, breaking a long-standing CLI test
convention
(and inconsistent with this same module's own NO_COLOR "blank means not
requested" convention). Blank bool-key env values now resolve to
`False`.
- `polylogue/storage/sqlite/queries/mappers_support.py` and
`polylogue/storage/blob_integrity.py`: PR #3155's three-tier JSON facade
introduced `polylogue.core.json.JSONDecodeError` (a `ValueError`
subclass,
NOT a stdlib `json.JSONDecodeError` subclass), but two call sites still
  caught the stdlib type — silently losing `DatabaseError` diagnostic
  wrapping (field/record id context) and blob-corruption graceful
  degradation since 2026-07-19.

**Stale test assertions / drifted mocks, fixed:**

- `tests/unit/cli/test_color_and_layout.py`: tested
`no_color_requested()`/
  `should_use_plain()` as if they read `NO_COLOR` from the environment
directly; PR #3079 made them pure passthroughs (env resolution moved to
`config.py`, already covered elsewhere). Rewrote to test the passthrough
  contract.
- `tests/unit/storage/test_durable_migrations.py`: hardcoded
`USER_SCHEMA_VERSION == 9` / `applied_versions` tuple; PR #3068 bumped
it
  to 10 without updating these two tests.
- `tests/unit/cli/__snapshots__/test_plain_cli_snapshots.ambr`: stale
  `index.db` `user_version`/`sqlite_stat1_rows` snapshot from before PR
  #3235's schema bump 42→43.
- `tests/unit/cli/test_diagnostics.py`: `_patch_tool_count_store`'s fake
`ArchiveStore.open_existing` lambda didn't accept the `read_timeout`
kwarg
  PR #2964 added, and the fake store was missing `begin_read_snapshot()`
  (also from #2964's interruptible-read protocol) — 8 tests broken since
  2026-07-17.
- `tests/unit/devtools/test_mandate_continuity_replay.py` and
`tests/unit/operations/test_work_effect_reconciliation.py`: both
asserted
the real `GitHubPullRequestEffectAdapter` fails against
`Sinity/polylogue`
— true only in an environment without `gh` auth (e.g. stock CI), false
on
any dev machine with `gh` authenticated for this repo (confirmed: `gh pr
list --repo Sinity/polylogue` succeeds fine here). Forced deterministic
  unavailability via a nonexistent `gh_path` instead.
- `tests/unit/storage/test_delegations_view.py`: 3 tests opened a bare
  `index.db`-only `ArchiveStore` (no `user.db`); PR #3068's new
`archive_snapshot_epoch()` unconditionally requires `user_tier`
attached.
Added a sibling `user.db` bootstrap to the 3 affected fixtures — matches
  every other test's full-tier archive construction.
- `tests/unit/architecture/test_surface_storage_boundary.py`:
allow-listed
  two CLI commands (`reconcile_work_effects.py`, and
  `materialize_incident_evidence.py` — the latter landed on master via a
concurrent session's PR #3336 mid-rebase) that construct
`SessionRepository`
  directly instead of through `AppEnv.repository`, per the test's own
  documented remediation path. Filed polylogue-a7uk for the proper fix.

**Concurrent-session note:** this branch was rebased onto master
mid-flight
after another session's PR #3332 landed fixing the exact same
`test_timestamp_guards.py` hypothesis-6.161 mypy break I'd independently
found and fixed — kept master's version (identical `st.one_of` split
approach) rather than duplicating it.

**Already tracked, not duplicated:**

- `test_execution_control.py` `api.query_units` naming mismatch +
  `>=50000 VM steps` anti-vacuity mutation tests → polylogue-1ldl (fully
root-caused 2026-07-20: PR #3018 made the mutation-under-test no longer
  expensive at this data scale).
- `test_live_batch_support.py` stale `failed=[...]` assertion →
polylogue-5202.
- `test_archive_maintenance_cli.py` / `test_daemon_cli.py` 6-node
cluster →
  polylogue-p5li.
- `tests/infra/surfaces.py` stale `list_sessions`/`search` MCP tool-name
  lookups (affects `test_retrieval_readiness_laws.py`,
  `test_cross_surface_agreement.py`) → polylogue-t46.8 (MCP tool-sprawl
  replacement epic; p6rz's own original text already called this
  out-of-scope).

**New follow-up beads filed (confirmed pre-existing, not this-session
regressions, but not safe/minimal to fix inline):**

- polylogue-57w4 — repair path still disagrees with converger on
  NULL-sort-key session-profile staleness (regresses PR #2900's own
  invariant; root cause not fully diagnosed).
- polylogue-lbgc — seeded-archive corpus build hits `database is locked`
under xdist parallel first-build (affects `test_plain_cli_snapshots.py`,
  `test_schema_generation.py`, likely others); confirmed not simple
cross-worker contention (the build already holds an exclusive flock
across
  the whole build+integrity-check section) — more likely an unclosed
  intra-process connection.
- polylogue-e6a0 — `test_index_v37_fast_forward.py`'s v36 fixture
predates
the `action_pairs` runtime index added by PR #3210; attempted fix
revealed
  the fixture's intended "before" shape needs the full same-version
  benign-DDL-convergence set, not just `ensure_runtime_indexes_sync` —
  reverted the attempt rather than ship an incomplete fixture.

No regression found from this session's headline PRs (query DSL AST
schema,
browser-capture approval flow, continuity replay wiring) — the two
GitHub
effect-adapter tests and the `materialize_incident_evidence.py` boundary
violation are environment/pattern issues in supporting test/command
code, not
in the new capability logic itself.

## Verification

- `devtools test` on every changed test file individually: all green
  (see per-file evidence above).
- `mypy --strict` on every changed `.py` file: clean.
- `ruff format --check` / `ruff check`: clean.
- Fresh `devtools verify --all` run against this branch in progress;
will
update this PR/polylogue-p6rz with the final authoritative count once it
  completes (~14 min runtime).

Ref polylogue-p6rz
@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.

  • 69.F094 / P2: fixed-already at the checked revision: polylogue/pipeline/services/ingest_batch/_core.py:3667-3677 now nests the SQLite connection transaction context inside closing. Successful receipt consumption therefore commits before connection close, while exceptions roll the transaction back.

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

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

  • 75.F028 / P2: fixed-already at the checked revision: The surviving storage-correctness scenario imports canonical FTS lifecycle helpers and search_messages at devtools/storage_correctness_scenario.py:25-26, and exercises them at :249-253. The deleted FTS5 provider import is absent from devtools, and the old lab/benchmark entry files are no longer the active consumers.

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