Repository navigation
fix(mcp): harden six-tool cutover — session correlation, status(operation), SessionStart preamble - #3095
Conversation
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Warning Review limit reached
Next review available in: 11 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the 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 configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: ⛔ Files ignored due to path filters (1)
📒 Files selected for processing (67)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Preserves the lane-C codex session's uncommitted working tree after the Codex quota cutoff: new polylogue/mcp/server_cutover.py plus declaration registry, server_support/server_tools, QueryTransaction, continuity harness, and generated agent-manual/reference surface changes. NOT verified — WIP preservation commit; state unknown mid-cutover. Co-Authored-By: Codex <[email protected]> Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01QUsH3Rhq6oAZpYPWcsZqnZ
… contract gaps Problem: the WIP six-tool cutover (server_cutover.py) collapsed the MCP read surface from ~97 individual tool registrations down to six declared transactions (query/read/get/explain/context/status), but left ~10 old test files pinned to the retired individual tool names plus real gaps in the new six-tool test coverage itself (286 failures characterized on polylogue-t46.8). What changed: - Deleted 10 old implementation-coupled MCP test files (test_tool_contracts.py and its dependents, test_user_state_tools.py, test_candidate_capture_tool.py, test_session_analysis_primitives.py, test_assertion_judgment_tools.py, test_facets_tool_contract.py, test_distilled_bundle_tools.py, test_session_tool_timing.py, test_insight_shape_tools.py, test_analysis_primitives_facade_parity.py). Each pinned a retired MCP tool registration whose underlying logic has independent coverage outside mcp/ (tests/unit/api/test_facade_contracts.py, test_session_analytics_facade.py, tests/unit/insights/test_otlp_correlation.py, test_postmortem.py, tests/unit/archive/test_facets.py, tests/unit/storage/test_*assertions*.py). - Removed the now-dangling test_tool_contracts.py references from devtools/validation_lane_catalog_contracts.py (9 lanes) and their pinning assertions in test_validation_lanes.py. - Fixed real bugs in the new six-tool test surface: test_tool_discovery.py's _KNOWN_MINIMAL dict and headline-tool assertion still listed old tool names (query/read/get/explain/context/status all take required args the generic invoke helper wasn't supplying); test_server_runtime.py had a stale mock assertion missing the services= kwarg from an unrelated code change; test_tool_error_isolation.py's registry sanity check still hardcoded old tool names. - Rewrote test_envelope_contracts.py's TOOL_CONTRACT classification matrix and TestNativeReadSurfaceHonorsContract for the six tools, verified against a real seeded archive. query classifies as an envelope (QueryUnitEnvelope shape); read/get/explain/context/status classify as single_object, matching their declared MCPResultSemantics in polylogue/mcp/declarations/registry.py. The seeded-archive test now installs real RuntimeServices rather than patching only _get_config, since query/context/explain route through the cached _get_polylogue() facade, not _get_config() alone. Verification: devtools test tests/unit/mcp/ tests/unit/archive/query/test_transaction.py tests/unit/devtools/test_validation_lanes.py — down from 286 failed/144 passed/6 skipped to remaining failures isolated to per-retired-tool test files not yet triaged (test_agent_coordination.py, test_aggregate_sessions.py, test_annotation_import_tool.py, test_annotation_join_tool.py, test_blackboard_tools.py, test_compose_context_preamble.py, test_context_image.py, test_contract_evidence.py, test_correlate_session.py, test_cost_outlook_tool.py, test_embedding_status_tool.py, test_logical_session_tool.py, test_mcp_call_log.py, test_mcp_edge_cases.py, test_per_tool_contracts.py, test_prompt_query_parity.py, test_tag_idempotency.py — next commit). Ref polylogue-t46.8, polylogue-t46.8.2 Co-Authored-By: Claude <[email protected]>
Problem: deleting the retired-tool test files in the prior commit left docs/plans/test-closure-matrix.yaml and test-coverage-domains.yaml pointing at the now-deleted tests/unit/mcp/test_tool_contracts.py, and docs/test-quality-workflows.md was stale relative to the new test tree. devtools verify --quick failed on closure-matrix, manifests, and render-all. What changed: - Repointed the mcp.surface/mcp_surface manifest rows at tests/unit/mcp/test_tool_discovery.py + test_envelope_contracts.py (the six-tool coverage) alongside the still-live test_server_surfaces.py/ test_mcp_edge_cases.py/test_mcp.py. - Regenerated docs/test-quality-workflows.md (devtools render quality-reference). - Rewrote TOOL_CONTRACT in test_envelope_contracts.py for the six cutover tools: query classifies as an envelope (QueryUnitEnvelope shape); read/get/explain/context/status classify as single_object, matching their declared MCPResultSemantics in polylogue/mcp/declarations/registry.py. TestNativeReadSurfaceHonorsContract now installs real RuntimeServices (not just a patched _get_config) since query/context/explain route through the cached _get_polylogue() facade. - Fixed a ruff SIM300 (yoda-condition) lint in the prior commit's test_tool_discovery.py edit. Verification: devtools verify --quick green (ruff format/check, mypy, render all --check, topology/layering/closure-matrix/manifests/ ci-workflows/doc-commands/docs-coverage/test-infra-currency/ test-clock-hygiene/pytest-timeout-overrides/degrade-loudly all exit 0). Ref polylogue-t46.8, polylogue-t46.8.2 Co-Authored-By: Claude <[email protected]>
…ion), retire remaining old-tool tests Problem: after the prior two commits fixed the six-tool test infrastructure itself (discovery, envelope contracts, contract evidence), 118 test failures remained across ~14 files, all pinning individual MCP tool registrations retired by the six-tool cutover (query/read/get/explain/context/status). Two real implementation gaps surfaced during that triage, not just stale tests. Real implementation fixes (polylogue/mcp/server_cutover.py): - get/read did not thread session_id into hooks.async_safe_call, so session-scoped call-log correlation (used by readiness/debugging surfaces) silently stopped working for every ref-based call -- a regression from the old get_session_summary/get_messages tools, which did thread it. Both now extract the session id from a `session:` ref and pass it through. - status(scope=...) declares 5 scopes (archive/sources/embeddings/ coordination/operation) but only ever populated archive stats regardless of the requested scope. Implemented scope="operation" to return the same readiness + mcp_call_delivery outbox-pressure payload the old readiness_check tool exposed (component_readiness, archive_convergence, checks). sources/embeddings/coordination remain unimplemented -- filed as residual scope. Test fixes: - Rewrote test_mcp_call_log.py's 3 daemon-backed production-route tests (success/typed-failure persistence, per-session correlation, outbox pressure) against the six tools using the session_id fix above. - Fixed prompt text: 4 prompts (decisions_about, unacknowledged_failures, sessions_touching_file) still taught agents to call the retired query_units(...) tool by name in their rendered call-sequence text -- renamed to query(...), the six-tool equivalent. Fixed test_prompt_query_parity.py's tool lookup to match. - Deleted 4 test_mcp_edge_cases.py cases (unicode tag via add_tag, empty query via search, limit=0/-1 via list_sessions) whose scenarios are already covered generically by test_tool_discovery.py's full six-tool parametrized sweep. - Deleted 12 test files testing retired individual tool registrations whose underlying logic has independent coverage confirmed outside mcp/: test_agent_coordination (coordination/test_envelope.py), test_aggregate_sessions (api/test_session_analytics_facade.py + several insights/ files), test_annotation_import_tool/test_annotation_join_tool (api/test_facade_contracts.py), test_blackboard_tools (storage/test_blackboard_facade.py), test_context_image (cli/test_context_image_view.py, 255 lines), test_correlate_session (insights/test_session_commit.py -- core algorithm; the retired tool only wrapped id-resolution and message-dict shaping), test_cost_outlook_tool (cost/test_contract_suite.py), test_embedding_status_tool (api/test_embedding_readiness_api.py + others), test_logical_session_tool (api/test_topology_api.py), test_tag_idempotency (storage/test_tag_contracts.py + others), test_per_tool_contracts (889 lines -- the entire mutation/write family is currently unregistered for every role pending polylogue-t46.8.3, so none of its scenarios are reachable through any live MCP surface right now). Not yet fixed: test_compose_context_preamble.py (654 lines) still fails -- build_context_preamble_payload has no coverage outside this MCP-tool-coupled file, so it cannot simply be deleted; next commit converts it to test the underlying function directly. Verification: devtools test tests/unit/mcp/ tests/unit/archive/query/test_transaction.py -- 12 failed (all test_compose_context_preamble.py), 153 passed, down from 286 failed/144 passed at session start. devtools verify --quick green. Ref polylogue-t46.8, polylogue-t46.8.2 Co-Authored-By: Claude <[email protected]>
Problem: the six-tool cutover collapsed the old compose_context_preamble tool into context(), but context()'s implementation only ever called context_image_payload (seed-query/seed-ref RAG-style compilation) -- build_context_preamble_payload (session lineage, ranked resume candidates, project git branch/commits, provenance-gated assertion guidance) had no call path left anywhere in the MCP surface. The `intent` parameter existed on context()'s signature but was immediately deleted/unused. This is a real capability loss, not test staleness: SessionStart hook context injection (this machine's own session-start recall hooks) was silently unreachable. What changed (polylogue/mcp/server_cutover.py): - context() gained repo_path/cwd/recent_files/session_id/limit parameters and now dispatches on intent: intent="resume" builds the SessionStart preamble via build_context_preamble_payload plus the git branch/commit enrichment the old tool did (moved from the now-dead server_context_tools.py registrar, which register_tools() no longer calls), everything else keeps the existing context-image behavior. - session_id (when the seed session is known) threads into hooks.async_safe_call for call-log correlation, matching the get/read fix from the prior commit. Test changes: renamed test_compose_context_preamble.py -> test_context_resume_intent.py and converted its 23 tests (12 previously failing, 11 already testing build_context_preamble_payload directly) to exercise context(intent="resume", ...) through the real registered tool instead of the retired compose_context_preamble registration. Verification: devtools test tests/unit/mcp/ tests/unit/archive/query/test_transaction.py -- 165 passed, 0 failed (was 286 failed/144 passed at the start of this PR's work). devtools verify --quick green. Ref polylogue-t46.8, polylogue-t46.8.2 Co-Authored-By: Claude <[email protected]>
…6.8.3)
Problem: polylogue-t46.8.3's PRIVILEGED_ALGEBRA (write/judge/run/maintenance)
was declared in mcp/declarations/registry.py but had zero implementation --
every MCP role saw only the six read tools. The old per-operation mutation
tools (add_tag, save_annotation, judge_assertion_candidate, maintenance_*,
...) were unregistered for every role, making the entire write/judgment/
maintenance surface unreachable through MCP.
What changed (polylogue/mcp/server_cutover.py):
- write(operation=..., session_id=, tag=, key=, value=, confirm=, fields=):
one declared transaction dispatching to 20 mutation operations
(add_tag/remove_tag/bulk_tag_sessions/set_metadata/delete_metadata/
delete_session/add_mark/remove_mark/save_annotation/delete_annotation/
capture_assertion_candidate/blackboard_post/import_annotation_batch/
save_saved_view/delete_saved_view/save_recall_pack/delete_recall_pack/
save_workspace/delete_workspace/record_correction/clear_corrections),
each a thin adapter over the same Polylogue facade method the retired
per-operation tool called. session_id/session_ids/tag/tags/key/value/
confirm cover the common cases; fields carries operation-specific values.
- judge(items=, candidate_ref=, decision=, ...): unifies the existing
judge_assertion_candidate/judge_assertion_candidates into one verb --
candidate_ref+decision is sugar for a one-item items list.
- run(ref=, limit=): executes a saved-query ref (saved-query:<id> /
saved-view:<id>) through the same session-search machinery query()
uses for its new sessions projection (see below).
- maintenance(operation=, ...): preview/execute/status/list/rebuild_index/
update_index/rebuild_insights, delegating to the existing planner/
registry (polylogue/maintenance/) unchanged.
- Role gating: register_cutover_privileged_tools checks mcp.role and only
registers write/run at role=write, +judge at role=review, +maintenance
at role=admin -- matches PRIVILEGED_ALGEBRA's declared minimum_role
ladder (write/review/write/admin) exactly.
- query(projection="sessions", origin=, tag=, repo=, since=, until=, sort=):
a second capability restoration alongside the privileged tools. query()
previously only wrapped query_units (message/action/block-level DSL
rows); there was no way to list or rank-search SESSIONS through the
six-tool surface at all (the retired search/list_sessions tools had no
replacement). projection="sessions" reuses the same
archive_search_payload/archive_session_list_payload machinery those
retired tools used -- ranked (top-k) when expression is free text,
exhaustive listing otherwise. run() builds on this directly.
Declaration registry (polylogue/mcp/declarations/registry.py):
- Added 4 _ToolRow entries (write/judge/run/maintenance) to
_CUTOVER_TOOL_ROWS, registrar="register_cutover_privileged_tools".
- Generalized _cutover_declaration (previously hardcoded for the six read
tools): capability is now f"{minimum_role}:{verb}" instead of a
hardcoded "read:" prefix; retirement_owner is t46.8.2 for read tools
and t46.8.3 for privileged ones (matching the existing pattern already
used for the historical ~103-row compatibility table); grammar/field/
value_discovery and resource_alternatives (which point at the read-only
polylogue://capabilities/query resource) and workflow/incident_coverage
(which named read-specific incident-replay test suites) are empty for
privileged tools rather than falsely inherited from the read rows;
handlers[].owner_path is derived from row.module instead of hardcoded
to server_cutover.py, since MCPToolDeclaration.__post_init__ requires
non-empty workflow_coverage -- privileged rows get a new honest label
("t46.8.3-privileged-contract") backed by this PR's own test file.
Test changes:
- New tests/unit/mcp/test_privileged_tools.py (22 tests): role-gating
matrix, write() happy-path + missing-field + unknown-operation +
fields-dict dispatch + delete_session confirm guard + saved-view
round-trip, judge() single-vs-bulk dispatch + validation, run() saved-
query execution + not-found + wrong-ref-kind, maintenance() list/status
validation, and query(projection="sessions") ranked-search + exhaustive-
listing + continuation-rejection -- all against a real seeded archive
via RuntimeServices, not mocks (matching the pattern from
test_envelope_contracts.py / test_contract_evidence.py).
- Updated test_tool_declarations.py's three tests that pinned "no
privileged tool exists yet" (one literally named
test_all_roles_expose_the_same_read_floor_until_privileged_cutover_lands)
to assert the real role ladder, module/registrar bindings for all 10
tools, and the regenerated 10-tool mcp-equivalence.json.
- Added write/judge/run/maintenance to test_envelope_contracts.py's
TOOL_CONTRACT classification matrix.
- Regenerated docs/generated/mcp-equivalence.json and docs/mcp-reference.md
(devtools render mcp-equivalence / mcp-tool-index).
Not done here: the old register_mutation_tools/register_personal_state_tools/
register_maintenance_tools/register_insight_tools/register_context_tools
registrar functions are intentionally left in place as dead code -- per
registry.py's own header comment ("t46.8.2 and t46.8.3 own the disjoint
retirement groups") they were compatibility/implementation substrate, and
this PR's write()/maintenance() dispatch reimplements their logic as thin
adapters rather than calling into them directly, so they are now fully
superseded and safe to delete in a follow-up cleanup pass. polylogue-t46.9
(OperationSpec as executable mutation authority) remains unimplemented --
this PR intentionally does not invent a parallel mutation policy.
Verification: devtools test tests/unit/mcp/ tests/unit/archive/query/test_transaction.py
-- 187 passed, 0 failed. devtools verify --quick green (ruff format/check,
mypy --strict, render all --check, topology/layering/closure-matrix/
manifests/ci-workflows/doc-commands/docs-coverage/test-infra-currency/
test-clock-hygiene/pytest-timeout-overrides/degrade-loudly).
Ref polylogue-t46.8, polylogue-t46.8.3
Co-Authored-By: Claude <[email protected]>
…aster Mechanical loc: line-count drift from files master and this branch both touched since the prior rebase (37bbdc5, ef1bc00, and other daemon/ webui/hermes commits landed on master in the meantime). Verification: devtools test tests/unit/mcp/ tests/unit/archive/query/test_transaction.py -- 187 passed; devtools verify --quick green. Co-Authored-By: Claude <[email protected]>
1962948 to
60bffa9
Compare
…3116) ## Summary Second PR for polylogue-20d.17: extends the budgeted component-snapshot protocol from PR #3107 (daemon/archive status) to the agent-coordination envelope, bounding its one genuinely expensive, unbounded stage. Scope narrowed mid-implementation after a real architectural discovery — see "Scope note" below. ## Problem Live measurement of `build_coordination_envelope` against the real (large, currently mid-restore) archive found its `archive_evidence` stage — session trees, activity episodes, subagent exchanges, proof refs, and context-flow refs, one read-only SQLite connection with no per-query timeout — taking **~10s**, while every other stage (repo, process, self, work_item, beads, peers, resources, archive, handoff, overlaps, advisories) stayed under 1s. Any caller of `build_coordination_envelope` paid this cost on every call, including the live `polylogue agents status` CLI command — the same "one slow probe stalls the whole answer" failure shape PR #3107 fixed for daemon status. ## Solution - `polylogue/coordination/envelope.py`: new `_bounded_stage` helper, backed by the shared `StatusComponentRegistry` protocol from PR #3107, wraps `archive_evidence` with a 3s deadline and an explicit degraded fallback (surfaced in the envelope's `advisories`) instead of blocking however long the query takes. The query keeps running on its own thread past the deadline (no cooperative cancellation for a blocking SQLite read), but the caller gets control back. - New `CoordinationEnvelopeCache` class (also `StatusComponentRegistry`- backed, fingerprint-invalidated on git HEAD/logs, `.beads/issues.jsonl`, and the active index db/WAL mtimes) is ready substrate for a future warm-cached coordination-status consumer. Not wired to a live surface in this PR — see below. ## Scope note (read this before reviewing the diff) This PR originally also rewired the MCP `agent_coordination` tool's ad-hoc 1s TTL-only cache onto `CoordinationEnvelopeCache`, mirroring PR #3107's MCP-cache treatment. While rebasing onto master (which had moved past a six-tool MCP surface cutover, `feature/mcp/retire-legacy-registrars`), I found that tool is **already dead code**: `register_tools()` — the actual live MCP server wiring in `polylogue/mcp/server.py` — only calls `register_cutover_read_tools`/`register_cutover_privileged_tools` from `server_cutover.py`, never `register_read_tools` (where `agent_coordination` lives). Its dedicated test file was already deleted by the six-tool cutover (#3095) with no replacement coverage, which is how this went unnoticed. The live, reachable coordination-status path today is `status(scope="coordination")` in `server_cutover.py` — and it has a separate, pre-existing bug: every scope value except `"operation"` falls through to the same generic `archive.stats()` projection, so `status(scope="coordination")` silently returns archive stats, never coordination data. Wiring `CoordinationEnvelopeCache` into that handler is real, valuable follow-up work, but it sits inside another lane's actively in-flight cutover and risks colliding with concurrent changes there. Filed as **polylogue-qink** instead of attempted here. ## Verification ``` devtools test tests/unit/coordination/ tests/unit/mcp/ # 199 passed mypy --strict polylogue/coordination/envelope.py polylogue/coordination/__init__.py # clean devtools verify --quick # green ``` Live-archive read-only measurement (provisional — archive mid-restore from the 2026-07-18 incident): | Path | Before | After | | --- | --- | --- | | `archive_evidence` stage (in-process) | ~10.0s (unbounded) | capped at the 3.0s deadline, degraded reason surfaced in `advisories` | | `polylogue agents status --format json` (live CLI, no MCP) | would be ~11s+ with the unbounded stage | ~5.1s (import tax + bounded stages) | Ref polylogue-20d.17
Ref polylogue-t46.8 Problem: the six-tool MCP cutover (#3095) replaced the ~97-tool registration surface with query/read/get/explain/context/status plus the privileged write/judge/run/maintenance transactions, but left the old per-operation registrar modules, their glue, and an inert ~103-row legacy declaration table sitting in the tree unused. What changed: - Deleted server_context_tools.py, server_insight_tools.py, server_maintenance_tools.py, server_mutation_tools.py, server_personal_state_tools.py (2,480 lines) — no role registers them; register_tools() only calls register_cutover_read_tools/ register_cutover_privileged_tools. - Relocated _build_mcp_scope_filter from server_maintenance_tools.py into server_cutover.py's maintenance() dispatch before deleting the source file. - Gutted server_tools.py to its 19-line register_tools() shim. - polylogue/mcp/declarations/registry.py: deleted the dead ~103-row _TOOL_ROWS table and its exclusively-supporting machinery (_WORKFLOW_COVERAGE, _PROMPT_ALTERNATIVES, _RESOURCE_ALTERNATIVES, _DISCOVERY, _CONTINUATION, _TARGET_ROUTE, _OBSERVED_USE, _validate_inventory_tables, _family_id, the never-called _build_declaration) — none of it fed MCP_TOOL_DECLARATIONS, which is built exclusively from the live _CUTOVER_TOOL_ROWS. Kept _ToolRow, _compatibility, and _python_parity, which _cutover_declaration still uses. 3716 -> 528 lines. - Repointed six operations/specs.py code_refs from the deleted server_mutation_tools.py/server_personal_state_tools.py functions to server_cutover._dispatch_write. - Rewrote two test_mcp_call_log.py tests to AST-parse server_cutover.py instead of the deleted per-tool modules, and deleted a third (test_every_session_tool_forwards_telemetry_identity) whose glob-scan premise — many individually-named @mcp.tool() functions, each with its own async_safe_call — no longer holds now that write()/ maintenance() collapse ~20 former per-operation tools into one dispatch with one call site; the two rewritten parametrized tests already cover the same telemetry-forwarding invariant for the collapsed shape. - Renamed test_query_tool_schema_derivation.py -> test_query_request_contracts.py, dropping 8 tests whose premise (deriving schemas from the deleted register_query_tools) no longer applies; kept 5 tests exercising MCPSessionQueryRequest/payload builders directly. - Regenerated docs/plans/topology-target.yaml and docs/topology-status.md (devtools render topology-projection / topology-status) to drop the five deleted files' rows. - Marked architecture-hotspots.md rows 8a/8b resolved. Verification: devtools test tests/unit/mcp/ tests/unit/verification/test_code_refs_resolve.py (368 passed); devtools verify --quick (all static gates green); mypy --strict and ruff clean on every touched file. Note: devtools verify --all surfaced a large body of pre-existing baseline failures unrelated to this diff (MCP tool-name test debt from drift from other recent master commits) — none reproduce from clearing stale fixture caches, none touch any file this diff modifies. Tracked separately, not fixed here to keep this PR's boundary to dead-code deletion. Co-Authored-By: Claude <[email protected]>
Ref polylogue-t46.8
Problem: devtools verify --all found ~20 tests across
tests/unit/storage/{test_surface_parity_adapters,test_query_parity}.py
and tests/unit/maintenance/{test_scope_filter_envelope_contract,
test_envelope_contracts,test_scope_filter}.py still calling the
individually-named MCP tools (list_sessions, search,
maintenance_preview) retired by the six-tool cutover (#3095),
deterministically failing with KeyError on every run since -- test
debt this session's earlier work left behind, never caught by
`devtools test tests/unit/mcp/` because these files live outside that
directory.
What changed:
- Extended query()'s tool signature and _query_sessions with
min_messages/max_messages/min_words, mirroring the existing
origin/tag/repo/since/until/sort filters -- test_surface_parity_adapters.py
needed these on the session-listing path and the old list_sessions
tool supported them, so this closes a real (if narrow) parameter gap
in query(projection="sessions", ...) rather than watering down the
parity test. Also threaded the same three fields through
_dispatch_run's saved-query replay for symmetry.
- Rewired _MCPSurface in both storage parity test files from
_tools["search"]/_tools["list_sessions"] to
_tools["query"].fn(expression=..., projection="sessions", ...) --
same underlying archive_search_payload/archive_session_list_payload
machinery, so response shape is unchanged.
- Rewired the three maintenance test files'
_tools["maintenance_preview"] call sites to
_tools["maintenance"].fn(operation="preview", ...), and fixed two
stale registration-presence assertions
(test_maintenance_tools_registered_on_admin_server /
test_maintenance_tools_absent_from_read_server) that were checking
for "maintenance_preview"/"maintenance_execute" -- names that never
existed post-cutover, so the assertions were vacuously true rather
than testing anything.
- Found and fixed a real production bug while doing this:
server_cutover.py's _build_mcp_scope_filter only had
MaintenanceScopeFilter imported under TYPE_CHECKING, but its body
constructs one at runtime -- every maintenance(operation="preview"
or "execute") call was raising NameError. Added the runtime import
to the function's existing lazy-import block.
- Marked test_mcp_cost_outlook_tool_uses_shared_envelope xfail
(strict=True, raises=KeyError): the cost_outlook tool has no
six-tool-surface replacement yet -- cost/usage rollup MCP wiring
needs a design decision explicitly deferred this session, tracked in
polylogue-hg97. This turns silent breakage into an honest, tracked
gap that auto-un-xfails once the design lands.
Filed polylogue-p6rz for the remaining ~40-file pre-existing failure
list from the same devtools verify --all run that are NOT MCP-related
(no_color_requested() signature drift, a stale migration-count
assertion, query_units telemetry-key naming) -- confirmed unrelated by
isolated reruns, left untouched here.
Verification: devtools test tests/unit/mcp/ tests/unit/maintenance/
tests/unit/storage/test_surface_parity_adapters.py
tests/unit/storage/test_query_parity.py tests/unit/cost/test_contract_suite.py
tests/unit/verification/test_code_refs_resolve.py (576 passed, 1
xfailed); mypy --strict and ruff clean; devtools render all --check
clean.
Co-Authored-By: Claude <[email protected]>
## Summary Deletes the ~7,000 lines of MCP registrar code and declarations that were made fully dead weight by the six-tool cutover (#3095) but never removed — the retired per-operation registrar modules, their glue, and an inert ~103-row legacy declaration table. ## Problem #3095 replaced the ~97-tool MCP surface with `query`/`read`/`get`/`explain`/ `context`/`status` plus the privileged `write`/`judge`/`run`/`maintenance` transactions. The tool *registrations* were removed (no role registers the old per-operation tools), but ~2,480 lines of registrar-module code, ~1,000 more dead lines in `server_tools.py`, and an inert ~103-row legacy declaration table in `registry.py` were left sitting in the tree unused. ## Solution - Deleted `server_context_tools.py`, `server_insight_tools.py`, `server_maintenance_tools.py`, `server_mutation_tools.py`, `server_personal_state_tools.py` (2,480 lines) — relocated `_build_mcp_scope_filter` into `server_cutover.py`'s `maintenance()` dispatch before deleting its source file. - Gutted `server_tools.py` to its 19-line `register_tools()` shim. - `polylogue/mcp/declarations/registry.py`: deleted the dead `_TOOL_ROWS` table (distinct from the live `_CUTOVER_TOOL_ROWS`) and its exclusively- supporting machinery (`_WORKFLOW_COVERAGE`, `_PROMPT_ALTERNATIVES`, `_RESOURCE_ALTERNATIVES`, `_DISCOVERY`, `_CONTINUATION`, `_TARGET_ROUTE`, `_OBSERVED_USE`, `_validate_inventory_tables`, `_family_id`, the never-called `_build_declaration`) — confirmed none of it feeds `MCP_TOOL_DECLARATIONS`, which is built exclusively from `_CUTOVER_TOOL_ROWS`. Kept `_ToolRow`/`_compatibility`/`_python_parity`, which `_cutover_declaration` still uses. 3,716 → 528 lines. - Repointed six `operations/specs.py` `code_refs` from the deleted `server_mutation_tools.py`/`server_personal_state_tools.py` functions to `server_cutover._dispatch_write`. - Rewrote two `test_mcp_call_log.py` tests to AST-parse `server_cutover.py` instead of the deleted per-tool modules, and deleted a third (`test_every_session_tool_forwards_telemetry_identity`) whose glob-scan premise — many individually-named `@mcp.tool()` functions, each with its own `async_safe_call` — no longer holds now that `write()`/`maintenance()` collapse ~20 former per-operation tools into one dispatch with one call site; the two rewritten parametrized tests already cover the same telemetry-forwarding invariant for the collapsed shape. - Renamed `test_query_tool_schema_derivation.py` → `test_query_request_contracts.py`, dropping 8 tests whose premise (deriving schemas from the deleted `register_query_tools`) no longer applies; kept 5 tests exercising `MCPSessionQueryRequest`/payload builders directly. - Regenerated `docs/plans/topology-target.yaml` / `docs/topology-status.md`; marked `architecture-hotspots.md` rows 8a/8b resolved. ## Verification - `devtools test tests/unit/mcp/ tests/unit/verification/test_code_refs_resolve.py` — 368 passed (the code-refs drift gate is the main risk surface for this diff). - `devtools verify --quick` — all static gates green (also re-ran on push via the pre-push hook). - `mypy --strict` / `ruff` clean on every touched file. - `devtools verify --all`: surfaced a large body of **pre-existing** baseline failures unrelated to this diff — MCP tool-name test debt from #3095 in files outside `tests/unit/mcp/` (`_tools["list_sessions"]`, `_tools["search"]`, `_tools["cost_outlook"]`, `_tools["maintenance_preview"]` still referenced by ~6 test files), plus unrelated CLI/migration drift from other recent master commits (`no_color_requested()` signature drift, a stale migration-count assertion). None reproduce from clearing stale fixture caches; none touch any file this diff modifies. Tracking the MCP-tool-name debt as an immediate follow-up PR; filing the unrelated drift separately rather than expanding this PR's scope. Ref polylogue-t46.8 --------- Co-authored-by: Claude <[email protected]>
Ref polylogue-t46.8
Problem: devtools verify --all found ~20 tests across
tests/unit/storage/{test_surface_parity_adapters,test_query_parity}.py
and tests/unit/maintenance/{test_scope_filter_envelope_contract,
test_envelope_contracts,test_scope_filter}.py still calling the
individually-named MCP tools (list_sessions, search,
maintenance_preview) retired by the six-tool cutover (#3095),
deterministically failing with KeyError on every run since -- test
debt this session's earlier work left behind, never caught by
`devtools test tests/unit/mcp/` because these files live outside that
directory.
What changed:
- Extended query()'s tool signature and _query_sessions with
min_messages/max_messages/min_words, mirroring the existing
origin/tag/repo/since/until/sort filters -- test_surface_parity_adapters.py
needed these on the session-listing path and the old list_sessions
tool supported them, so this closes a real (if narrow) parameter gap
in query(projection="sessions", ...) rather than watering down the
parity test. Also threaded the same three fields through
_dispatch_run's saved-query replay for symmetry.
- Rewired _MCPSurface in both storage parity test files from
_tools["search"]/_tools["list_sessions"] to
_tools["query"].fn(expression=..., projection="sessions", ...) --
same underlying archive_search_payload/archive_session_list_payload
machinery, so response shape is unchanged.
- Rewired the three maintenance test files'
_tools["maintenance_preview"] call sites to
_tools["maintenance"].fn(operation="preview", ...), and fixed two
stale registration-presence assertions
(test_maintenance_tools_registered_on_admin_server /
test_maintenance_tools_absent_from_read_server) that were checking
for "maintenance_preview"/"maintenance_execute" -- names that never
existed post-cutover, so the assertions were vacuously true rather
than testing anything.
- Found and fixed a real production bug while doing this:
server_cutover.py's _build_mcp_scope_filter only had
MaintenanceScopeFilter imported under TYPE_CHECKING, but its body
constructs one at runtime -- every maintenance(operation="preview"
or "execute") call was raising NameError. Added the runtime import
to the function's existing lazy-import block.
- Marked test_mcp_cost_outlook_tool_uses_shared_envelope xfail
(strict=True, raises=KeyError): the cost_outlook tool has no
six-tool-surface replacement yet -- cost/usage rollup MCP wiring
needs a design decision explicitly deferred this session, tracked in
polylogue-hg97. This turns silent breakage into an honest, tracked
gap that auto-un-xfails once the design lands.
Filed polylogue-p6rz for the remaining ~40-file pre-existing failure
list from the same devtools verify --all run that are NOT MCP-related
(no_color_requested() signature drift, a stale migration-count
assertion, query_units telemetry-key naming) -- confirmed unrelated by
isolated reruns, left untouched here.
Verification: devtools test tests/unit/mcp/ tests/unit/maintenance/
tests/unit/storage/test_surface_parity_adapters.py
tests/unit/storage/test_query_parity.py tests/unit/cost/test_contract_suite.py
tests/unit/verification/test_code_refs_resolve.py (576 passed, 1
xfailed); mypy --strict and ruff clean; devtools render all --check
clean.
Co-Authored-By: Claude <[email protected]>
…3121) ## Summary Fixes ~20 tests left broken by the six-tool MCP cutover (#3095) that still call individually-named MCP tools which no longer exist, and fixes a real production bug (`NameError`) found while doing so in `maintenance()`'s preview/execute path. **Stacked on #3118** (dead-code cleanup) — base branch is `feature/mcp/retire-legacy-registrars`, not `master`. Merge #3118 first. ## Problem `devtools verify --all` (the first full run since #3095 merged) found `tests/unit/storage/{test_surface_parity_adapters,test_query_parity}.py` and `tests/unit/maintenance/{test_scope_filter_envelope_contract, test_envelope_contracts,test_scope_filter}.py` still calling `server._tool_manager._tools["list_sessions"|"search"|"maintenance_preview"]` — tools retired by the cutover. Deterministic `KeyError` on every run, confirmed via isolated reruns (not a fixture-cache artifact). Never caught by `devtools test tests/unit/mcp/` because these files live outside that directory, and per-PR CI skips the heavy test suite entirely. ## Solution - Extended `query()`'s signature and `_query_sessions` with `min_messages`/`max_messages`/`min_words`, mirroring the existing `origin`/`tag`/`repo`/`since`/`until`/`sort` filters — closes a real (narrow) parameter gap in `query(projection="sessions", ...)` rather than weakening the parity test, since the old `list_sessions` tool supported these. Also threaded through `_dispatch_run`'s saved-query replay for symmetry. - Rewired both storage parity files' `_MCPSurface` from `_tools["search"]`/`_tools["list_sessions"]` to `_tools["query"].fn(expression=..., projection="sessions", ...)` — same underlying payload-building machinery, response shape unchanged. - Rewired the three maintenance test files' `_tools["maintenance_preview"]` call sites to `_tools["maintenance"].fn(operation="preview", ...)`, and fixed two registration-presence assertions that were checking for names (`maintenance_preview`/`maintenance_execute`) that never existed post-cutover — vacuously true, testing nothing. - **Found and fixed a real production bug**: `server_cutover.py`'s `_build_mcp_scope_filter` only had `MaintenanceScopeFilter` imported under `TYPE_CHECKING`, but constructs one at runtime — every `maintenance(operation="preview"/"execute")` call was raising `NameError`. Added the runtime import to the function's existing lazy-import block. - Marked `test_mcp_cost_outlook_tool_uses_shared_envelope` `xfail` (`strict=True`, `raises=KeyError`): `cost_outlook` has no six-tool-surface replacement yet — cost/usage rollup MCP wiring needs a design decision explicitly deferred this session, tracked in `polylogue-hg97`. Filed `polylogue-p6rz` for the remaining ~40-file pre-existing failure list from the same `--all` run that are **not** MCP-related (`no_color_requested()` signature drift, a stale migration-count assertion, `query_units` telemetry-key naming) — confirmed unrelated by isolated reruns, left untouched here. ## Verification - `devtools test tests/unit/mcp/ tests/unit/maintenance/ tests/unit/storage/test_surface_parity_adapters.py tests/unit/storage/test_query_parity.py tests/unit/cost/test_contract_suite.py tests/unit/verification/test_code_refs_resolve.py` — 576 passed, 1 xfailed. - `mypy --strict` / `ruff` clean. - `devtools render all --check` clean. Ref polylogue-t46.8 Co-authored-by: Claude <[email protected]>
) ## Summary The Nix devshell's `mypy` entry in `buildInputs` silently shadowed the uv.lock-pinned mypy 2.3.0 with the Nix store's 1.20.1, hiding real strict-mypy findings locally that CircleCI's bare-Docker quick-gate would catch. ## Problem `devShells.default.buildInputs` listed `mypy` directly (a Python library package). mkShell's Python setup hooks add such packages' site-packages to `PYTHONPATH`, and `PYTHONPATH` entries are consulted before a venv's own site-packages when Python builds `sys.path`. So `.venv/bin/mypy` (and any `uv run mypy`) ran the Nix-provided 1.20.1 instead of the correctly-installed 2.3.0 in `.venv`, even inside an activated devshell. This is exactly the class of drift PR #3077 hit and fixed for `polylogue/` on CircleCI: findings invisible locally, red on CI. Running the real 2.3.0 against the full `[tool.mypy] files` config (`polylogue`, `tests/**`, `devtools/**` — CircleCI checks `polylogue/` only) surfaced two further findings CI has never covered: - `tests/unit/coordination/test_envelope.py:215` — a real mypy narrowing limitation: after `key in {tuple_a, tuple_b, tuple_c}` narrows a tuple, mypy only tracks one alternative's literal type for a later subscript (`key[1]`), so a subsequent sibling `if key[1] == "gate":` is flagged as comparing non-overlapping literals even though the runtime behavior is correct. - `tests/unit/cost/test_contract_suite.py:203` — a tautological assertion (`!= "exact"`) already entailed by the preceding `in {"priced", "partial"}` check on the same narrowed value. ## Solution - Drop `mypy` from the devshell's `buildInputs`. `.venv` (via `uv sync --extra dev`) is already the sole mypy provider; the Nix copy served no purpose except colliding with it. - `test_envelope.py`: bind the tuple element to an explicit `str` local (`subcommand: str = key[1]`) before comparing, which stops mypy from carrying an overly narrow literal type across the two sibling checks. No runtime behavior change. - `test_contract_suite.py`: delete the redundant assertion; the preceding line already proves it. - `.gitignore`: add `.dmypy.json`, the dmypy daemon state file that a now-actually-working `dmypy` invocation creates at the repo root (alongside the existing `.mypy_cache/` entry). ## Verification - `nix develop --command bash -c 'python3 -c "import mypy; print(mypy.__file__, mypy.__version__)"'` → resolves to `.venv/.../mypy` at 2.3.0 (was the Nix store's 1.20.1 before this change). - `nix develop --command uv run mypy polylogue/` → clean (matches CircleCI, whose 3 original findings were already fixed by #3077). - `nix develop --command devtools verify --quick` → 17/17 steps green, `exit_code: 0`. - `devtools test tests/unit/coordination/test_envelope.py tests/unit/cost/test_contract_suite.py` → 40 passed. 1 pre-existing failure unrelated to this change (`KeyError: 'cost_outlook'` in `test_mcp_cost_outlook_tool_uses_shared_envelope`) reproduces identically with these edits stashed out — MCP six-tool-cutover registry drift from #3095, not touched by this PR. Ref polylogue-i0ep
…ver (#3132) ## Summary Closes the three documented "Known gaps" from PR #3095's six-tool MCP read algebra: no way to list personal-state records back, no postmortem/pathology reports, and `status(scope="sources"/"embeddings")` silently falling through to archive stats. ## Problem PR #3095 replaced the ~97-tool MCP surface with six read transactions (`query`/`read`/`get`/`explain`/`context`/`status`) plus four privileged transactions. It shipped with a documented "Known gaps" section admitting three read capabilities lost no equivalent dispatch in the new surface: 1. Personal-state listing (marks/annotations/saved-views/recall-packs/workspaces/corrections/blackboard notes) — `write()` could create these records but nothing could list them back. 2. Postmortem/pathology reports — the retired `get_postmortem_bundle`/`get_pathologies` tools had no successor. 3. `status(scope="sources"/"embeddings")` — declared in the `status()` signature but both silently fell through to the same `scope="archive"` payload. All three were confirmed "trivial": the underlying `Polylogue` facade calls stayed live and independently tested through the cutover (unchanged by it); only the MCP dispatch wiring was missing. ## Solution All changes are in `polylogue/mcp/server_cutover.py`: - **`query(projection=...)`** gains 7 personal-state projections (`marks`, `annotations`, `saved_views`, `recall_packs`, `workspaces`, `corrections`, `blackboard`), each a thin dispatch onto the existing `list_*` facade call + `page_items` + the existing typed payload class (`MCPUserMarkListPayload` etc., which survived the cleanup PR unused). Offset pagination is not yet exposed (mirrors the existing `projection="sessions"` precedent, which also fixes offset at 0). - **`query(projection=...)`** gains `postmortem`/`pathologies`, reusing `build_session_query_request`'s filter scaffolding and dropping the MCP default page limit (`replace(spec, limit=None)`) before handing the spec to the 200-session analysis cap — the same trick the retired `get_postmortem_bundle`/`get_pathologies` tools used, otherwise the shared page-size default of 10 silently caps the matched scope and defeats the facade's own analysis cap. Also adds `abandoned_sessions`/`stuck_sessions` as two more thin projections (no semantic overlap found with postmortem/pathologies, so kept separate per the plan's documented fallback). - **`status(scope="sources")`** wires the existing `named_source_freshness` handler through the already-unused `ref` parameter (single-source by design, matching the retired tool's own scope). - **`status(scope="embeddings")`** wires `embedding_status_payload` via a small `_EmbeddingStatusEnv` config adapter (mirrors the retired `embedding_status` tool), with `include=("detail",)`/`include=("bands",)` mapping to its `include_detail`/`include_retrieval_bands` params. Rebased onto master after #3128 landed a fifth `status()` scope (`coordination`) concurrently — merged cleanly since it's a disjoint `if scope == ...` branch in the same function; also updated `status()`'s docstring to describe all four now-wired non-archive scopes. No new MCP declaration rows needed: `query`/`status` already exist in `TARGET_DEFAULT_READ_ALGEBRA` with result-semantics broad enough to cover the new projections/scopes (documented in each function's docstring, matching the `context(intent="resume")` precedent). ## Verification - `devtools test tests/unit/mcp/` — 184 passed (16 new, in `tests/unit/mcp/test_query_gap_projections.py`). - `devtools verify --quick` — green (format/lint/mypy --strict/render-all-check). - Live read-only smoke pass (`POLYLOGUE_ARCHIVE_ROOT=~/.local/share/polylogue` via `sinnix-scope background`, same pattern as #3095) against the real ~18k-session archive: all 12 new projections/scopes returned valid payloads with no errors — `postmortem`/`pathologies` matched 153 sessions over the last 7 days, `abandoned_sessions` found 74, `status(scope=embeddings)` reported real catch-up state (`total_sessions=2498`), `status(scope=sources)` returned a real freshness projection. Ref polylogue-t46.8.2 🤖 Generated with [Claude Code](https://claude.com/claude-code)
#3171 The 2026-07-18 residual-gap note on polylogue-z9gh.9.1 flagged HTTP/API query_units continuation as unwired. Investigation found both already fixed by the same day's later six-tool cutover commit (dc6fa63/#3095); PR #3171 closes the remaining test-coverage gap that note actually left open. Bead stays in_progress (not closed) per the mission's own instruction -- z9gh.9.1 has broader open scope beyond this slice. Ref polylogue-z9gh.9.1
## Summary Verifies and locks in test coverage for continuation-resume parity across Polylogue's three query_units surfaces (daemon HTTP `/api/query-units`, the Python API `Polylogue.query_units()` facade, and the MCP `query` tool). ## Problem polylogue-z9gh.9.1's 2026-07-18 trail note flagged a residual gap: daemon HTTP's `/api/query-units` accepts no `continuation` query parameter (no resume path exists there, even though it returns a continuation token), and the Python API/CLI `query_units` path likewise has no continuation input. MCP already accepts and validates continuation via `validate_continuation_epoch()`/`QueryContinuationStaleError`, the reference implementation. Source review found both flagged gaps already closed on master, just not reflected in the bead trail: the six-tool MCP cutover hardening pass (`dc6fa632a` / #3095, merged the same day, *after* the note was written) added continuation decoding + `QueryContinuationStaleError` handling to both `DaemonAPIHandler._handle_query_units` and `Polylogue.query_units`, reusing the same `query_units_transaction_request` / `QueryTransaction` / `QueryContinuation` primitives MCP's `query` tool already validated — and in fact MCP's `query` tool delegates straight into `Polylogue.query_units` under the hood, so there was never a second implementation to build. What was missing was direct proof that this held together end-to-end: HTTP had its own continuation test suite (`tests/unit/daemon/test_web_reader.py`), and only MCP+API were compared together (`tests/unit/mcp/test_server_surfaces.py`) — no test drove all three surfaces against the same corpus, and the Python API facade's own `continuation=` keyword had zero direct test coverage (only indirect coverage via MCP tests that patch the facade in). ## Solution - `tests/unit/api/test_facade_contracts.py`: four new tests pinning `Polylogue.query_units(continuation=...)` directly — normal resume drains all rows with stable `query_ref`/`result_ref`, rejecting a continuation combined with a new expression (`QueryContinuationInvalidError`), rejecting a continuation issued before a write lands (`QueryContinuationStaleError`), and rejecting a malformed token. - `tests/unit/archive/query/test_continuation_surface_parity.py` (new): seeds one on-disk corpus, then drives HTTP, the Python API facade, and the MCP `query` tool through an identical expression/continuation flow, asserting byte-identical `message_id` ordering and identical `query_ref`/`result_ref` across all three pages, plus identical `query_continuation_stale` rejection when a write lands between issuing and resuming a continuation on each surface. No production code changed — this closes the residual test-coverage gap the bead trail identified, without building a second continuation mechanism (the mission's explicit anti-goal): every surface still funnels through the single `query_units_transaction_request`/`QueryTransaction` boundary. **Not touched — CLI:** the CLI does not call `Polylogue.query_units` at all today. Its `find`/`read` verbs use a separate `SessionQuerySpec` / `cli/archive_query.py` path with plain `limit`/`offset`, not opaque continuation tokens. There is no CLI query-units paging surface to wire continuation resume into, so CLI is out of this change's scope. **Reviewed but not touched — z9gh.3 execution-layer gaps:** the two execution-layer gaps flagged in polylogue-z9gh.3's notes (`near:""` similarity queries falling back to an unfiltered session list; `lineage:id:` queries not materializing declared `parent_refs`/`child_refs`/`continuation` projection columns) both live in the generic find/read CLI route (`expression.py`, `execution_control.py`, `unit_results.py` untouched by that prior PR), not in the HTTP/API/MCP `query_units` continuation path this change touches. Left as already-tracked scope, not duplicated here. ## Verification - `devtools test tests/unit/archive/query/test_continuation_surface_parity.py tests/unit/api/test_facade_contracts.py tests/unit/mcp/test_server_surfaces.py` — 286 passed. - `devtools test tests/unit/daemon/test_web_reader.py::TestReaderQueryUnits` — 13 passed (confirms no regression to the existing HTTP continuation suite from sharing its `xdist_group`). - `devtools verify --quick` — green, 16/16 steps (ran automatically via the pre-push hook too). - `mypy --strict` on both new/changed test files — clean. - Noted, not caused by this change: `devtools test tests/unit/daemon/test_web_reader.py` run as a whole has one pre-existing failure (`TestReaderAssertionEndpoint::test_operational_web_payloads_redact_configured_archive_paths`, `sqlite3.OperationalError: unable to open database file` after the test deliberately unlinks `index.db` mid-run) — reproduced identically at `origin/master` HEAD (`71d134eaa`) with none of this PR's files present, confirming it predates this change. Ref polylogue-z9gh.9.1, polylogue-z9gh.9 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added continuation support for paging query results across the Python API, HTTP endpoint, and MCP tool. * Query pages preserve consistent ordering and shared query/result identifiers when resumed. * **Bug Fixes** * Invalid, conflicting, malformed, or stale continuation tokens are now consistently rejected. * Stale continuations return appropriate errors across all supported query interfaces. * **Tests** * Added coverage for multi-page queries and cross-interface result and error consistency. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
… projections
Problem: two production smokes exposed one missing contract on default
analysis projections. `analyze --cost-outlook` returned a syntactically
valid but operationally useless `null` with only an ad hoc `reason:
no_cycle_anchor` key and no remediation when a plan had no
`cycle_anchor_day`. `analyze --facets` took 17.8s with no signal that a
"cheap default" projection had blown any budget.
What changed:
- New `polylogue.insights.projection_contracts` registry declares, per
default projection, its cost/detail class (cheap/expensive), default
interactive deadline, and prerequisites with remediation text
(`cost-outlook`, `facets`, `facets-deferred`).
- New shared `ProjectionAvailabilityPayload`/`ProjectionPrerequisitePayload`
envelope (`polylogue/surfaces/payloads.py`) reports state
(ready/degraded/unavailable), reason, remediation, and measured
cost (deadline_s/elapsed_s/budget_exceeded) alongside a projection's data.
- `Polylogue.facets()` now measures wall-clock execution and reports the
declared cost class/deadline/elapsed/budget_exceeded on `FacetsResponse`
(`cost_class`, `deadline_s`, `elapsed_s`, `availability`); this
automatically reaches the `/api/facets` daemon/HTTP route since it
serializes the same response model.
- `analyze --cost-outlook` (CLI) replaces the ad hoc `{"reason":
"no_cycle_anchor"}` dict with the typed `availability` envelope on both
the missing-prerequisite and success paths, in JSON and plain-text output.
- `--explain` on `analyze --facets`/`--cost-outlook` surfaces the declared
contract (cost class, deadline, prerequisites) via the existing terminal
pipeline `args` payload.
Deferred (documented, not silently dropped):
- Bounded/resumable execution for expensive facet families is explicitly
out of scope here — that QoS mechanism belongs to the shared query
transaction (polylogue-z9gh.9). Expensive families satisfy AC #3's
"opt-in, or a bounded resumable reference" via the existing
`--include-deferred` opt-in gate, not a new resumable-reference type.
- MCP: no `cost_outlook`/`facets` MCP tool exists today (the standalone
`cost_outlook` tool was retired in polylogue-t46.8/#3095, tracked for a
design decision in polylogue-hg97), so there is nothing to wire there yet.
- Other `analyze` modes (count/by/postmortem/portfolio) have no declared
contract; `--explain` intentionally omits `projection_contract` for them
rather than fabricating one.
Verification:
- `devtools test tests/unit/insights/test_projection_contracts.py
tests/unit/cli/test_cost_outlook_cli.py tests/unit/cli/test_click_app.py
tests/unit/cli/test_plain_cli_snapshots.py` — 121 passed (the only
failures are `test_json_status_snapshot`, pre-existing drift unrelated to
this diff, and 8 `sqlite3.OperationalError: database is locked` errors in
postmortem/portfolio tests caused by a concurrent sibling worktree's
`devtools verify --seed-testmon` contending on the shared
`/dev/shm`/`/realm/tmp/polylogue-pytest` seeded-db cache).
- `devtools test tests/unit/daemon/test_web_reader.py -k facets` — 19
passed (route/facade parity test updated to also strip the now-volatile
`elapsed_s` wall-clock field, same treatment as the existing
`generated_at` exclusion).
- `mypy --strict` on touched files — clean.
- `devtools render all --check` — sync OK (new payload models picked up by
generated `cli-output-schemas`/`openapi` without extra registration; new
module regenerated `docs/plans/topology-target.yaml`).
- `devtools verify --quick` — exit 0.
Ref polylogue-duti
Co-Authored-By: Claude <[email protected]>
… projections (#3198) ## Summary Default analysis projections (`analyze --facets`, `analyze --cost-outlook`) now declare their cost/detail class, default interactive deadline, and prerequisites, and report an explicit `ready`/`degraded`/`unavailable` state instead of an opaque null or a silently slow success. ## Problem Two production smokes exposed one missing `ProjectionSpec` contract (polylogue-duti): - `analyze --cost-outlook` returned a syntactically valid but operationally useless `null` (with only an ad hoc `{"reason": "no_cycle_anchor"}` key) when a plan had no `cycle_anchor_day` — no typed remediation. - `analyze --facets` took 17.8s with no signal that a "cheap default" projection had blown any budget. ## Solution - New `polylogue.insights.projection_contracts` registry: `ProjectionContract` declares cost class (cheap/expensive), default interactive deadline, and prerequisites with remediation for `cost-outlook`, `facets`, and `facets-deferred`. - New shared `ProjectionAvailabilityPayload`/`ProjectionPrerequisitePayload` envelope (`polylogue/surfaces/payloads.py`): `state` (ready/degraded/unavailable), `reason`, `detail`, `remediation`, `deadline_s`/`elapsed_s`/`budget_exceeded`, and per-prerequisite satisfaction. - `Polylogue.facets()` measures wall-clock execution and stamps `cost_class`/`deadline_s`/`elapsed_s`/`availability` onto `FacetsResponse` — this reaches the `/api/facets` daemon/HTTP route for free since it serializes the same response model. - `analyze --cost-outlook` CLI replaces the ad hoc `{"reason": "no_cycle_anchor"}` dict with the typed `availability` envelope on both the missing-prerequisite and success paths (JSON and plain text). - `--explain` on `analyze --facets`/`--cost-outlook` surfaces the declared contract (cost class, deadline, prerequisites) through the existing terminal-pipeline `args` payload. ### Deliberately deferred (not silently dropped) - Bounded/resumable execution for expensive facet families is out of scope here — that QoS mechanism belongs to the shared query transaction (polylogue-z9gh.9). AC #3's "opt-in, or a bounded resumable reference" is satisfied via the existing `--include-deferred` opt-in gate, not a new resumable-reference type. - No MCP tool wiring: no `cost_outlook`/`facets` MCP tool exists today (the standalone `cost_outlook` tool was retired in polylogue-t46.8/#3095; MCP cost/usage design tracked in polylogue-hg97), so there is nothing to wire yet. - Other `analyze` modes (`--count`, `--by`, `--postmortem`, `--portfolio`) have no declared contract; `--explain` intentionally omits `projection_contract` for them rather than fabricating one. ### AC matrix (polylogue-duti) 1. Every default analysis ProjectionSpec declares prerequisites/cost class/deadline/degraded semantics — **satisfied** for the two projections named in the bead's evidence (`cost-outlook`, `facets`); other `analyze` modes deliberately out of scope (no evidence of a smoke against them). 2. `cost-outlook` without a cycle anchor returns a typed unavailable result with remediation across CLI and machine payloads — **satisfied**. 3. `facets` with default families meets its declared interactive budget; expensive families are opt-in — **satisfied** (opt-in already existed; this PR adds the declared deadline + measured `budget_exceeded` signal so a regression is now visible instead of silent). Resumable-reference alternative deliberately not built (see deferred above). 4. `explain` exposes prerequisite/cost decisions; all surfaces adapt the same outcome — **satisfied for CLI** (`--explain` + JSON/plain output); HTTP gets it for free via the shared `FacetsResponse` model; MCP has no tool to adapt (deferred, tracked in polylogue-hg97). 5. Seeded missing-prerequisite and slow-family mutations fail the production-route tests — **satisfied**: `test_no_cycle_anchor_returns_json_null_outlook` asserts the typed unavailable envelope; `test_analyze_facets_reports_degraded_when_it_misses_its_declared_budget` monkeypatches the clock through the real CLI route and asserts `degraded`/`budget_exceeded` — this is a genuine mutation-proof regression test for the exact 17.8s smoke. ## Verification - `devtools test tests/unit/insights/test_projection_contracts.py tests/unit/cli/test_cost_outlook_cli.py tests/unit/cli/test_click_app.py tests/unit/cli/test_plain_cli_snapshots.py` — 121 passed. Remaining failures are pre-existing/environmental: `test_json_status_snapshot` (unrelated drift — this PR does not touch status.py and the diff to that test file is purely additive elsewhere) and 8 `sqlite3.OperationalError: database is locked` errors in postmortem/portfolio tests caused by a concurrent sibling worktree's `devtools verify --seed-testmon` contending on the shared `/dev/shm`/`/realm/tmp/polylogue-pytest` seeded-db cache. - `devtools test tests/unit/daemon/test_web_reader.py -k facets` — 19 passed (route/facade parity test updated to also strip the now-volatile `elapsed_s` field, same treatment as the existing `generated_at` exclusion). - `mypy --strict` on touched files — clean. - `devtools render all --check` — sync OK (new payload models picked up by generated `cli-output-schemas`/`openapi` with no extra registration needed; new module triggered a `docs/plans/topology-target.yaml` regeneration). - `devtools verify --quick` — exit 0 (also re-ran clean via the pre-push hook). Ref polylogue-duti <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added readiness and availability details to facets and cost-outlook analysis results. * Added cost classifications, timing, budget status, prerequisites, remediation guidance, and degraded-state reporting. * Added projection contract details to `analyze --explain`. * Added terminal readiness indicators and clearer messages for unavailable or over-budget results. * **Documentation** * Updated topology and status documentation to reflect current project mappings and totals. * **Tests** * Added coverage for projection contracts, availability states, budget handling, and CLI output. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Claude <[email protected]>
## Summary Closure package for the `polylogue-t46.8` MCP verb-algebra epic's children: `polylogue-t46.8.2` (read migration) and `polylogue-t46.8.3` (privileged families). Both beads' 2026-08-19 pass-2 notes agreed the implementation is done (103-tool-to-10-verb collapse shipped in PR #3095, `dc6fa632a`) and what remains is proof runs plus one documentary report. This PR is exactly that: no production code changed. ## Problem Both beads' AC lists were last touched before the collapse's supporting test harnesses existed or were last run together. The 2026-08-19 pass-2 notes named specific unrun/unmeasured items: - `t46.8.2` AC#2 (seven continuity drills + z9gh Workflow incident replay) and AC#3 (bounded pages/continuation for oversized cases) had harnesses (`test_cold_model_continuity_replay.py` ×2, `test_tool_discovery.py`, `test_bounded_query_transport.py`) that existed but were "unrun in this audit". - `t46.8.3` AC#5 (t8t coordination/context flows plus negative unauthorized/injection/retry fixtures) named four fixture files (`test_privileged_tools.py`, `test_tool_error_isolation.py`, `test_context_delivery_tool.py`, `test_status_scope_coordination.py`) in the same unrun state. - `t46.8.3` AC#6 (final surface/token-cost/usage report naming every retained exception) was flagged as "genuine unbuilt scope". - Both beads' AC#4 (per-tool production goldens/shadow telemetry proving no capability loss **before** deletion) is structurally unsatisfiable now — the old surface is already deleted, so there is no "before" left to shadow against. ## Solution - Ran all eight named test files individually via `devtools test`, sequentially, in this freshly-provisioned worktree off `origin/master`. All green — see the results table below. - Wrote `docs/mcp-surface-report-2026-08.md`: the final 10-tool + 15-URI- resource surface, per-tool declared operations (measured live against `polylogue/mcp/declarations/registry.py`/`server_cutover.py`), the capability-flag role-gating matrix, measured token cost of the serialized tool declarations under each capability combination (via a real `build_server()` + `list_tools()` call, not an estimate from memory), every retained exception with its reason, and AC#4 restated as misframed-not-satisfiable with the post-hoc parity evidence available instead. - Registered the report in `devtools/docs_surface.py`'s tiered doc index (archive tier, same precedent as the existing dated retros) and linked it from `docs/mcp-reference.md`. `devtools render all` regenerated `docs/README.md`'s index entry as a result — included in the diff. No MCP production code was touched. If any suite had been red, per the dispatch instructions this PR would have stopped at classification (pre-existing vs. revealing) rather than fixing MCP internals here — none were. ## Verification | Suite | AC | Result | | --- | --- | --- | | `tests/integration/test_cold_model_continuity_replay.py` | t46.8 AC#3 | 3 passed | | `tests/unit/devtools/test_cold_model_continuity_replay.py` | t46.8 AC#3 | 10 passed | | `tests/unit/mcp/test_tool_discovery.py` | t46.8.2 AC#2 | 9 passed | | `tests/unit/mcp/test_bounded_query_transport.py` | t46.8.2 AC#3 | 1 passed | | `tests/unit/mcp/test_privileged_tools.py` | t46.8.3 AC#5 | 60 passed | | `tests/unit/mcp/test_tool_error_isolation.py` | t46.8.3 AC#5 | 6 passed | | `tests/unit/mcp/test_context_delivery_tool.py` | t46.8.3 AC#5 | 6 passed | | `tests/unit/mcp/test_status_scope_coordination.py` | t46.8.3 AC#5 | 2 passed | | **Total** | | **97 passed, 0 failed** | `devtools verify --quick` — clean (format + lint + mypy + render-all-check, including the new doc registration + regenerated `docs/README.md` index + layering + schema policy + promotion audit). Full `devtools verify` not run: no production code changed (docs + a one-line devtools registry entry only), and this worktree's testmon graph would need a full bootstrap with nothing to gain from it — same digest-drift reasoning as the concurrent #4013 PR's gate substitution. ## Per-AC honesty breakdown (for the coordinator's own closing bookkeeping) This PR's pr-scope carrier marks both `t46.8.2` and `t46.8.3` **satisfied** per the dispatch's stated criterion ("SATISFIED if suites green + report lands"). That criterion covers the ACs this task was actually scoped to prove. It does **not** mean every AC on either bead's full text is proven by this PR — listed honestly below so the parent `t46.8`'s close (the coordinator's own bookkeeping, not this PR's) has the complete picture. **t46.8.2:** - AC#1 (equivalence coverage) — not re-verified this pass; prior sessions' notes claim it, not independently re-checked here. - AC#2 (continuity drills + Workflow replay) — **satisfied**, proof run above. - AC#3 (bounded pages, no row cap) — **satisfied**, proof run above. - AC#4 (pre-deletion goldens) — **misframed**, restated in the report (Section 5) with post-hoc parity evidence instead. - AC#5 (≤15-tool default profile) — **satisfied**, structurally (6 base tools), confirmed in the report (Section 1). - AC#6 (migration harness protects the shared transaction) — **not evidenced by this pass**; no suite here specifically targets removal/ mutation of the shared query transaction failing the harness. - AC#7 (concurrent incident-scale calls, cancellation/disconnect, bounded RSS/PSS/swap/temp, zero leaks) — **not evidenced by this pass**; none of the eight suites run here are a load/leak-proof harness. If this AC needs its own proof run, it is a residual, not covered by "SATISFIED" per the dispatch's own naming of what this task covers. **t46.8.3:** - AC#1 (every family maps onto a declared verb, no lost operation) — **substantially evidenced**: the report's Section 4 names three operations (`delete_saved_view`, `import_annotation_batch`, `deliver_context`) not covered by the specific executor-routing proof test class, and `maintenance()`'s entire operation surface has zero `OperationExecutor` routing (real, acknowledged, explicitly deferred to `kwsb.2`/`t46.9`) — not a silent gap, but also not a clean 100%. - AC#2 (prompt/resource content cannot acquire instruction/write authority) — not re-verified this pass. - AC#3 (candidate/judged state, idempotency, dry-run/authorization, receipts, status/recovery, role isolation) — **satisfied** by `test_privileged_tools.py`'s 60 passing tests, which cover this ground directly (confirm-gates, actuator routing, role gating). - AC#4 (old tools/aliases removed) — **satisfied**: confirmed live in the report that the five old registrar modules are fully deleted. - AC#5 (t8t flows + negative fixtures) — **satisfied**, proof runs above. - AC#6 (final surface/token-cost/usage report) — **satisfied**, this PR's report. ## Bead disposition matrix | Bead | Disposition | Evidence | Notes | | --- | --- | --- | --- | | polylogue-t46.8.2 | **SATISFIED** per dispatch criterion — close-candidate | commit (this PR); 4 test files, 23 passed; `docs/mcp-surface-report-2026-08.md` | AC#6/#7 (migration-harness protection, concurrent/leak-proof load test) not evidenced by this pass — see honesty breakdown above. Coordinator's call whether those warrant a residual bead before the parent closes. | | polylogue-t46.8.3 | **SATISFIED** per dispatch criterion — close-candidate | commit (this PR); 4 test files, 74 passed; `docs/mcp-surface-report-2026-08.md` | `maintenance()` executor-routing debt and 3 uncovered `write()` operations are real, named, and explicitly deferred to `kwsb.2`/`t46.9` per the bead's own prior notes — not new information, not blocking this bead's own AC (which asks for the mapping + report, not for `t46.9` to have landed). | The parent `polylogue-t46.8`'s close is the coordinator's own bookkeeping, per the dispatch — not attempted here. <!-- polylogue-pr-scope:v2 { "assigned_beads": [ "polylogue-t46.8.2", "polylogue-t46.8.3" ], "dispositions": [ { "bead_id": "polylogue-t46.8.2", "disposition": "satisfied", "evidence": [ { "kind": "commit", "ref": "eb3592edd" }, { "kind": "test", "ref": "tests/integration/test_cold_model_continuity_replay.py" }, { "kind": "test", "ref": "tests/unit/devtools/test_cold_model_continuity_replay.py" }, { "kind": "test", "ref": "tests/unit/mcp/test_tool_discovery.py" }, { "kind": "test", "ref": "tests/unit/mcp/test_bounded_query_transport.py" }, { "kind": "diff", "ref": "docs/mcp-surface-report-2026-08.md" } ], "successors": [] }, { "bead_id": "polylogue-t46.8.3", "disposition": "satisfied", "evidence": [ { "kind": "commit", "ref": "eb3592edd" }, { "kind": "test", "ref": "tests/unit/mcp/test_privileged_tools.py" }, { "kind": "test", "ref": "tests/unit/mcp/test_tool_error_isolation.py" }, { "kind": "test", "ref": "tests/unit/mcp/test_context_delivery_tool.py" }, { "kind": "test", "ref": "tests/unit/mcp/test_status_scope_coordination.py" }, { "kind": "diff", "ref": "docs/mcp-surface-report-2026-08.md" } ], "successors": [] } ], "mutated_beads": [], "scope_digest": "05d807ef6bdefe91359e9431035a016f3de33d54bf8f47b643a6a88304274574", "scope_kind": "bead", "version": 2 } -->
Summary
Finishes and hardens the six-tool MCP read surface (
query/read/get/explain/context/status— polylogue-t46.8.1/t46.8.2), inherited as a mid-implementation WIP from a Codex session cut off by quota exhaustion. Retires the test debt left by the cutover, fixes two real capability regressions discovered during that work, and validates the result against the live archive.Problem
The inherited WIP (
server_cutover.py,mcp/declarations/registry.py) collapsed the ~97-tool MCP surface down to six declared transactions, but:add_tag,search,list_sessions, …) that no longer exist, but also real bugs in the new six-tool test infrastructure itself (missing minimal-kwargs entries, stale mock assertions).get/readnever threadedsession_idinto the shared call-log wrapper), and the entire SessionStart-preamble workflow (session lineage, ranked resume candidates, project git state, provenance-gated assertion guidance) that the retiredcompose_context_preambletool served —context()'sintentparameter existed on the signature but was immediately deleted/unused.status(scope=...)declared 5 scopes but only ever populated archive stats regardless of the requested scope.Solution
Test debt (5 commits,
polylogue/mcp/*,tests/unit/mcp/*,devtools/validation_lane_catalog_contracts.py,docs/plans/*.yaml):mcp/(facade/API/CLI/storage tests) for each one.test_tool_discovery.py's_KNOWN_MINIMALdict and headline-tool assertion still referenced old tool names;test_envelope_contracts.py'sTOOL_CONTRACTclassification matrix and native-read-surface test rewritten for the six tools, verified against a real seeded archive;test_contract_evidence.py's error/no-result/registration-drift families rewritten for the six-tool shape; stale mock assertions intest_server_runtime.py/test_tool_error_isolation.py.server_prompts.pystill teaching agents to call the retiredquery_units(...)tool by name in their rendered call-sequence text.docs/plans/test-*.yamlmanifests after the deletions.Real implementation fixes (
polylogue/mcp/server_cutover.py):get/readnow thread the ref's session id intohooks.async_safe_call, restoring session-scoped call-log correlation.status(scope="operation")now returns the readiness +mcp_call_deliveryoutbox-pressure payload the oldreadiness_checktool exposed.context(intent="resume", repo_path=, cwd=, recent_files=, session_id=, limit=)restores the SessionStart preamble viabuild_context_preamble_payloadplus the git branch/commit enrichment moved out of the now-deadserver_context_tools.pyregistrar.Verification
devtools test tests/unit/mcp/ tests/unit/archive/query/test_transaction.py— 165 passed, 0 failed (was 286 failed / 144 passed at session start).devtools verify --quick— green (ruff format/check, mypy, render-all-check, topology/layering/closure-matrix/manifests/ci-workflows/doc-commands/docs-coverage/test-infra-currency/test-clock-hygiene/pytest-timeout-overrides/degrade-loudly).sinnix-scope background,POLYLOGUE_ARCHIVE_ROOT=/home/sinity/.local/share/polylogue):status/explain/context(intent="resume")all work correctly against the real 18,796-session archive.query()currently fails against the live archive — not a bug in this branch, see below.Not fixed here (filed separately)
archive_root/index.dbpath stuck on a stale 4-session snapshot while the real 18,796-session data sits in an unpromoted generation reachable only via.index-active-pointer. Separately,query_unit_frame_state(the z9gh.9.1 epoch-tracking table the newQueryTransactioncontinuation mechanism requires) doesn't exist on the live index at all, soquery()— the most important of the six tools — is completely non-functional against the live archive right now. Needs an operator-authorizedpolylogue ops reset --index && polylogued run, not something to run blind from this PR.write/judge/run/maintenanceprivileged transaction tools are declared (PRIVILEGED_ALGEBRAinregistry.py) but have zero implementation — every role currently sees only the six read tools. The oldregister_mutation_tools/register_personal_state_tools/register_maintenance_tools/register_insight_tools/register_context_toolsregistrar functions are intentionally retained as compatibility/implementation substrate for that future work, not dead code to delete.list_sessions/searchtools returned session rows;query()only wrapsquery_units, which explicitly rejectssessionsas a terminal source) — flagged as a design question, not fixed.Ref polylogue-t46.8, polylogue-t46.8.1, polylogue-t46.8.2
🤖 Generated with Claude Code
https://claude.ai/code/session_018RTQkmrFBkRqtB1JE3it3a