Skip to content

feat(query): bound agent-facing archive reads - #3018

Merged
Sinity merged 9 commits into
masterfrom
feature/fix/bounded-agent-queries
Jul 17, 2026
Merged

Sinity merged 9 commits into
masterfrom
feature/fix/bounded-agent-queries

Conversation

@Sinity

@Sinity Sinity commented Jul 17, 2026 •

Copy link
Copy Markdown
Owner

Summary

Implements the z9gh archive-query load-safety slice, t8t continuity replay catalog, and directly related MCP query design in one bounded read contract.

Problem

Under real agent load, valid archive reads could block the event loop, materialize archive-wide action/delegation relations, erase oversized successful results, lose filter state in recovery, fabricate totals from capped pages, or leave agents without executable query discovery and known-answer continuity evidence.

Solution

  • Added the shared interruptible, admission-controlled SQLite read transaction with opaque query/result refs, exact/inexact total semantics, advancing q1 continuations, cancellation/deadline handling, and cleanup receipts.
  • Routed archive reads across the Python API, CLI, daemon HTTP, MCP tools/resources/prompts, annotations, demo verification, search, messages, sessions, topology, and insight adapters through the controlled read boundary. Writer paths remain explicitly read-write.
  • Replaced archive-wide action/delegation query materialization with indexed rebuildable action_pairs and delegation_facts projections plus compatibility views, scoped refresh triggers, and bounded SQL aggregate paths.
  • Added executable MCP query discovery/resource metadata, corrected query recipes, bounded message pages, cursor request identity validation, replayable oversized envelopes, and nullable totals where the retrieval lane cannot prove an exact count.
  • Added seven continuity scenarios plus the parallel-Claude incident fixture with independent fixture-owned answer/mutation oracles, exact known-answer population checks, and non-progressing continuation mutation checks.
  • Regenerated MCP/OpenAPI/CLI/topology generated surfaces.

Verification

  • devtools verify --quick passed: format, lint, strict mypy, render-all, topology, layering, schema, manifest, docs, and policy gates.
  • Focused post-merge behavioral sweep: 67 passed across execution control, transaction replay, MCP transport/envelopes, action/delegation storage, multi-field aggregates, and continuity scenarios.
  • Prior affected-area sweep: 1030 passed, 1 skipped, 1 deselected; the deselected test targets an unrelated nonexistent-archive redaction fixture and returns HTTP 500 before this change's route.
  • devtools render all and the pre-push quick gate passed after synchronization with current origin/master.
  • Live worktree-source query against the configured archive returned a bounded 3-row page with exact indexed total=4237 and an advancing continuation.

Compatibility

The index tier remains rebuildable; no durable migration is introduced. Public actions and delegations view names remain available. Similarity/semantic retrieval totals are nullable when the lane cannot prove an exact total. Legacy search cursors without request identity remain readable; new cursors bind the complete request identity.

Known evidence boundary

The continuity proof is deterministic fixture-derived and independently graded; no private 4.85-million-block live replay was run in this change. The known-answer incident census is preserved in tests/data/continuity/incident.json for the authorized live terminal gate.

Refs: z9gh, t8t.

Summary by CodeRabbit

  • New Features
    • Added stable query references, result references, and continuation tokens to query responses.
    • Improved pagination across CLI and MCP search, query, and message results.
    • Added bounded response pages that respect output-size limits while providing advancing continuation guidance.
    • Added query capability discovery through MCP resources.
    • Enhanced message results with block evidence, filtering, timestamps, and accurate totals.
  • Bug Fixes
    • Search cursors now reject reuse with incompatible query criteria.
    • Improved archive read cancellation, cleanup, and consistency.
  • Documentation
    • Updated API and output schemas for new pagination fields.

Problem: agent-facing archive reads could block the event loop, materialize archive-wide action/delegation relations, or lose useful results at the MCP response boundary.\n\nWhat changed: add one resumable query transaction identity and continuation contract over the existing interruptible executor; route core MCP/API/resource reads through it; replace global action/delegation compatibility views with indexed derived cohorts refreshed per affected session or parent; generate a query capability resource; and add independent continuity scenario oracles. Generated schemas, OpenAPI, MCP equivalence, and topology projections are refreshed.\n\nCompatibility/migration: index schema version 38 rebuilds the derived index tier; compatibility actions/delegations view names remain unchanged.\n\nCo-Authored-By: Claude <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 17, 2026 •

Copy link
Copy Markdown

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: ad2931a3-4371-421d-a16d-585837b012c2

📥 Commits

Reviewing files that changed from the base of the PR and between 1948346 and 8ca8047.

⛔ Files ignored due to path filters (1)
  • docs/generated/mcp-equivalence.json is excluded by !**/generated/**
📒 Files selected for processing (45)
  • devtools/continuity_replay.py
  • docs/openapi/search.yaml
  • docs/plans/topology-target.yaml
  • docs/schemas/cli-output/query-unit-aggregate-envelope.schema.json
  • docs/schemas/cli-output/query-unit-envelope.schema.json
  • docs/topology-status.md
  • polylogue/annotations/join.py
  • polylogue/api/archive.py
  • polylogue/api/insights.py
  • polylogue/archive/query/archive_execution.py
  • polylogue/archive/query/execution_control.py
  • polylogue/archive/query/search_hits.py
  • polylogue/archive/query/transaction.py
  • polylogue/archive/query/unit_results.py
  • polylogue/cli/archive_query.py
  • polylogue/cli/commands/diagnostics.py
  • polylogue/cli/commands/maintenance/_archive_read.py
  • polylogue/cli/read_views/standard.py
  • polylogue/cli/shell_completion_values.py
  • polylogue/daemon/http.py
  • polylogue/demo/verify.py
  • polylogue/mcp/archive_support.py
  • polylogue/mcp/declarations/registry.py
  • polylogue/mcp/payloads.py
  • polylogue/mcp/server_prompts.py
  • polylogue/mcp/server_resources.py
  • polylogue/mcp/server_support.py
  • polylogue/mcp/server_tools.py
  • polylogue/product/continuity_scenarios.py
  • polylogue/storage/sqlite/action_pairs.py
  • polylogue/storage/sqlite/archive_tiers/archive.py
  • polylogue/storage/sqlite/archive_tiers/index.py
  • polylogue/storage/sqlite/archive_tiers/write.py
  • polylogue/storage/sqlite/delegation_facts.py
  • polylogue/surfaces/payloads.py
  • tests/data/continuity/incident.json
  • tests/unit/archive/query/test_read_surface_control.py
  • tests/unit/archive/query/test_transaction.py
  • tests/unit/cli/test_query_exec_laws.py
  • tests/unit/mcp/test_bounded_query_transport.py
  • tests/unit/mcp/test_envelope_contracts.py
  • tests/unit/mcp/test_query_tool_schema_derivation.py
  • tests/unit/mcp/test_server_surfaces.py
  • tests/unit/product/test_continuity_scenarios.py
  • tests/unit/storage/test_archive_tiers_ddl.py

📝 Walkthrough

Walkthrough

The PR centralizes archive reads through query transactions, adds continuation-aware pagination and bounded MCP responses, materializes SQLite action and delegation projections, exposes query capability metadata, and introduces fixture-based continuity replay scenarios with CLI evaluation.

Changes

Archive query and pagination

Layer / File(s) Summary
Controlled archive-read boundary
polylogue/archive/query/*, polylogue/api/*, polylogue/cli/*, polylogue/daemon/http.py
Archive reads use shared transaction/context helpers with operation metadata, projections, stable ordering, workload classes, cancellation guards, and cleanup.
MCP query and message surfaces
polylogue/mcp/server_*.py, polylogue/mcp/archive_support.py
MCP resources and tools use query transactions, support bounded message pages, expose query capabilities, and preserve nullable totals for retrieval paths without exact counts.
Response identity and continuation
polylogue/archive/query/transaction.py, polylogue/archive/query/unit_results.py, polylogue/surfaces/payloads.py, polylogue/mcp/server_support.py
Query/result references, continuation tokens, request-bound search cursors, and byte-budget page narrowing are added to response flows.
SQLite derived projections
polylogue/storage/sqlite/*, polylogue/storage/sqlite/archive_tiers/*
Action pairs and delegation facts are materialized and refreshed through schema tables, triggers, guards, and session-write hooks. Message queries also expose block evidence and filtered counts.
Continuity replay verification
polylogue/product/continuity_scenarios.py, devtools/continuity_replay.py, tests/data/continuity/*, tests/unit/product/*
Fixture-derived scenarios define expected refs, answers, mutations, budgets, and classifications; a CLI evaluates recorded observations against those oracles.

Estimated code review effort: 5 (Critical) | ~120 minutes

Possibly related issues

Possibly related PRs

Suggested labels: type:refactor, area:storage

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/fix/bounded-agent-queries

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

Sinity added 8 commits July 17, 2026 14:36
Problem: legacy Python archive list and search adapters executed more filters than their bounded transaction identity recorded, so a replay descriptor could not faithfully describe the request.\n\nWhat changed: include every structural filter, normalized action/message value, and date bound in the shared transaction arguments while retaining limit and offset as page state.\n\nCompatibility/migration: no public signature or storage behavior changes.
Problem: archive reads outside the initial MCP and API routes could still open unbounded stores directly, including fluent queries, diagnostics, prompts, HTTP handlers, and insight/annotation helpers. One annotation join also held a store across asynchronous ref resolution.\n\nWhat changed: extend the shared transaction with synchronous context adapters, migrate the remaining read surfaces, preserve writer-only direct opens, and keep archive connections scoped to controlled work. Search-hit and fluent query helpers now reuse an already-controlled store when a caller has one.\n\nCompatibility/migration: read behavior and payloads remain unchanged; write routes keep their existing single-writer path.\n\nCo-Authored-By: Claude <[email protected]>
Problem: continuity acceptance had only shallow fixture refs, and the capability catalog exceeded the MCP response budget while cookbook prompts taught parser-invalid sessions-only expressions.\n\nWhat changed: add independent known-answer metadata and mutation classifications to the continuity scenarios, make the replay script runnable directly, add a route-bypass architecture guard, publish compact MCP read algebra/authority/coverage discovery, and correct the two invalid query recipes.\n\nCompatibility/migration: the existing scenario and tool inventories remain compatible; the capability resource keeps its URI and now returns a compact first response.\n\nRef polylogue-t8t\nRef polylogue-z9gh.3\n\nCo-Authored-By: Claude <[email protected]>
Problem: strict typing caught optional timestamp serialization, closure narrowing in exact CLI reads, and fixture-owned replay refs typed as arbitrary objects.\n\nWhat changed: narrow those values at their production boundaries without changing payload semantics.\n\nRef polylogue-z9gh.9.1\n\nCo-Authored-By: Claude <[email protected]>
Problem: bounded CLI list and search envelopes reported the number of rows in the current page as the archive total. This made a resumable page look complete under live archive load and hid the remaining result set. The new shared read-control path also exposed lightweight adapter doubles that lacked optional store lifecycle methods.\n\nWhat changed: lexical and browse pages now use the indexed count primitives inside the same controlled read transaction. Semantic and hybrid pages report an honest unknown total. The synchronous control adapter tolerates minimal store doubles while retaining progress guards and cleanup for real ArchiveStore instances. Added a production CLI regression covering a one-row page with a two-row match set.\n\nCompatibility/migration: no wire shape change; total was already nullable. Existing incomplete adapters receive null rather than a fabricated page-length total.\n\nVerification: devtools test tests/unit/cli/test_query_exec_laws.py; affected suite 756 passed, 1 skipped; direct continuity replay passed; live worktree-source replay reported total 4237 for a three-row page.
Problem: the first bounded-read pass still left composite action and delegation aggregates materialized in Python, emitted unusable continuations, hydrated full message transcripts on MCP reads, and allowed stale derived outcomes or fabricated similarity totals. Continuity replay also did not verify fixture-owned answer and mutation evidence.\n\nWhat changed: route composite aggregates through SQLite, consume and rebase q1 continuations, bind ranked cursors to request identity, expose honest unknown totals, page ordinary MCP messages with bounded block projections, preserve lineage semantics, refresh delegation cohorts when child profiles or block outcomes change, and validate replay answers and mutation cases.\n\nCompatibility/migration: similarity totals are now nullable when no exact count exists; legacy cursor tokens without request identity remain readable. Derived action/delegation tables are refreshed by the existing write triggers; no durable-tier migration is required.\n\nRef #z9gh\nRef #t8t
Keep the MCP budget continuation rebasing path type-safe for both row-item and message-page payloads.\n\nRef #z9gh
Preserve the bounded archive-read transaction and resumable MCP query
transport while incorporating the current master-side execution receipts,
aggregate metadata, and generated topology projection.

The merge also keeps lightweight archive doubles compatible with the shared
read boundary and records exact result-page evidence for bounded query work.

Ref z9gh
Ref t8t
@Sinity
Sinity marked this pull request as ready for review July 17, 2026 15:11
@Sinity
Sinity merged commit 9163d01 into master Jul 17, 2026
1 of 2 checks passed
@Sinity
Sinity deleted the feature/fix/bounded-agent-queries branch July 17, 2026 15:14

@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: 8ca80473df

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread polylogue/mcp/server_tools.py Resolved
Comment on lines +1078 to +1080
parent_session_id TEXT NOT NULL REFERENCES sessions(session_id) ON DELETE CASCADE,
child_session_id TEXT REFERENCES sessions(session_id) ON DELETE SET NULL,
mapping_state TEXT NOT NULL,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Refresh delegation facts when a child session is deleted

When delete_sessions() removes a child session, this FK only nulls child_session_id; there is no session_links DELETE trigger or other refresh of the surviving parent cohort. The materialized row consequently retains its old resolved mapping_state, child model, cost, token, wall-time, and terminal-state values even though the child and link are gone, whereas the former view recomputed the delegation as unmatched. Deleting a child can therefore return internally inconsistent delegation evidence until an unrelated parent refresh occurs.

Useful? React with 👍 / 👎.

Comment on lines +674 to +676
messages = []
for row in rows:
message = SessionMessagePayload.from_archive_row(row, session_id=resolved_session_id)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve message metadata in the bounded MCP projection

For ordinary non-lineage sessions, get_messages now converts ArchiveMessageQueryRow objects that contain none of the full-envelope metadata consumed by from_archive_row. As a result, existing messages are reported with has_tool_use, has_thinking, and has_paste_evidence falsely set to false, while attachment refs, parent ids, token usage, model, raw id, and source path are silently dropped. The bounded SQL projection needs to select and populate these fields (or derive the structural flags from its fetched blocks) before replacing the previous full-session path.

Useful? React with 👍 / 👎.

Comment on lines +7578 to 7580
WHERE {" AND ".join(predicates)}
ORDER BY m.position {order_direction}, m.variant_index {order_direction}, m.message_id {order_direction}
LIMIT ? OFFSET ?

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Retain chronological ordering across multiple sessions

When query_session_messages receives more than one session id, ordering solely by per-session position interleaves unrelated sessions by ordinal rather than by occurrence time. The CLI temporal-evidence reader calls this method for a set of summaries, labels the transaction order as time,message_id, and applies a global limit, so this change can select a different, non-chronological subset and omit events that should fall inside the temporal window. Keep the prior timestamp-first ordering for multi-session reads or provide a separate position-ordered single-session path.

Useful? React with 👍 / 👎.

Sinity added a commit that referenced this pull request Jul 20, 2026
## Summary

Fixes the polylogue-z9gh.2 F-006/F-007 residual: a session-scoped action/delegation query (e.g. `actions where session.id:X AND is_error:true`, or the `| group by followup_class | count` variant) could still plan an archive-wide `idx_blocks_type_tool` scan of every `tool_use`/`tool_result` block in the archive, instead of a cheap session-scoped index seek — even after PR #3018 (z9gh.2) replaced the old windowed-view `actions` relation with the `action_pairs`-backed one and added exact-session-id extraction from the query predicate.

## Problem

Investigation (`polylogue-z9gh` evidence matrix) flagged this residual as "unconfirmed-fixed." Root-causing it found the predicate-lowering side was already correct: `_exact_session_ids_from_predicate` / `_action_relation_for_query` (`polylogue/storage/sqlite/archive_tiers/archive.py`) already narrow a `session.id:X` predicate to an exact session bound for both the plain-count and the follow-up-relation-needing (`followup_class`) paths.

The residual was physical, not logical: `action_relation_select_sql` (`polylogue/storage/sqlite/action_relation.py`) had no way to *force* SQLite onto the session-scoped index, and a fresh `ArchiveStore`-bootstrapped archive never seeds `sqlite_stat1` — `initialize_archive_tier` (`polylogue/storage/sqlite/archive_tiers/bootstrap.py`) just runs `conn.executescript(spec.ddl)` with no `ANALYZE`/stat seeding, unlike the separate connection-pool bootstrap in `polylogue/storage/sqlite/schema.py` (`_ensure_schema`, which does seed `PLANNER_STAT1_SEED_SQL` — this is a genuinely different bootstrap path used elsewhere, not the one `ArchiveStore()` goes through). Without stats, SQLite's planner defaults to the low-cardinality `idx_blocks_type_tool (block_type=?)` index for the `block_type = 'tool_use'` predicate inside the bounded relation's ranking CTEs, regardless of how selective the session bound is. Empirically confirmed via `EXPLAIN QUERY PLAN` against a fresh archive: a single-session query planned the identical full `idx_blocks_type_tool` scan as an unbounded one.

## Solution

`action_relation_select_sql` now pins `INDEXED BY idx_blocks_session_position` on every `blocks` scan branch (`ranked_uses`, `ranked_results`, and the null-tool-id UNION ALL branch) whenever the relation is session-bounded (`session_placeholders` is set). The exact session id(s) are already known at SQL-generation time in this code path, so the correct index isn't a matter of cost estimation — it's pinned directly. The unbounded branch (used by the intentionally archive-wide flagship `actions where is_error:true | group by followup_class | count` example) is untouched.

New regression test `test_bounded_action_relation_plans_session_index_not_archive_wide_tool_scan` (`tests/unit/storage/test_archive_tiers_archive.py`) asserts via `EXPLAIN QUERY PLAN` (captured through `sqlite3.Connection.set_trace_callback` on the real `query_unit_counts` production call) that every `SEARCH u`/`SEARCH r` step in the bounded relation uses `idx_blocks_session_position`, never `idx_blocks_type_tool`. Anti-vacuity: verified the test fails with the exact pre-fix symptom (`SEARCH u USING INDEX idx_blocks_type_tool (block_type=?)`) when run against the unmodified `action_relation.py`.

### Investigated but not implemented: z9gh.3's near:/lineage: execution-layer gaps

The z9gh.3 bead (as narrowed) also names two `find`/`read`-route gaps: `near:"..."` similarity falling back to an unfiltered list, and `lineage:id:` recursive-page projection columns (`parent_refs`/`child_refs`/`continuation`) going unmaterialized. Both were investigated in depth (not skipped):

- **`near:id:`/`near:"text"`**: traced the full execution path (`polylogue/archive/query/archive_execution.py`). Current master already fails loudly (`ExpressionCompileError`) when `near:id:<ref>` needs a vector backend that isn't configured or a seed session with no stored embeddings (`_session_seed_scored`'s explicit docstring contract), and gracefully degrades to an *empty* semantic leg — not an unfiltered list — when no vector provider exists for a pure-`near:"text"` query (`_semantic_hits`'s documented #1743 graceful-degradation contract). `_archive_summaries` dispatches `plan.similar_session_id` before the text-semantic leg, correctly. A real end-to-end CLI test exists for the text-seeded leg (`test_async_execute_query_archive_uses_vector_provider_for_semantic_search`) but not for the session-seeded leg — a test-coverage gap, not a reproduced execution bug. Separately, `near:id:` used inside a `sessions where ...` scoping predicate at the `query_units`/DSL pipeline level currently raises `ExpressionCompileError("field 'near' is not supported inside Boolean SQL predicates yet")` — again fail-loud, not silent. Could not reproduce the "falls back to an unfiltered session list" symptom against current master through any of these paths; it may already have been fixed by since-landed work, similar to the stale `polylogue-2qx.2` bd state the evidence-matrix pass found and corrected.
- **`lineage:id:` recursive-page columns**: confirmed real. `lineage:id:X` *does* correctly filter session/message membership through `QueryLineagePredicate`/`_lineage_predicate_clause` (`polylogue/storage/sqlite/archive_tiers/archive.py`), but the declared "recursive-page" result semantics in the discovery corpus (`polylogue/archive/query/discovery.py`, `RECURSIVE_COLUMNS = ("session_id", "parent_refs", "child_refs", "continuation")`) promise graph-navigation columns and independent recursive pagination that the actual route never materializes — it returns a flat, non-recursively-paged row set. Building real `parent_refs`/`child_refs`/continuation-cursor graph pagination is a genuinely large, separate feature (new response shape, cycle-aware traversal, continuation state), not a surgical fix — sizing it S/M would be dishonest. Per the coordinator's explicit stop condition, this item is reported rather than force-fixed here.

No changes were made for either near:/lineage: item; recommend the polylogue-z9gh.3 bead be re-verified against current master (the near: gap) and, if still wanted, split into its own properly-scoped feature bead (the lineage: recursive-page projection) rather than carried as this residual's scope.

## Verification

- `devtools test tests/unit/storage/test_archive_tiers_archive.py -k test_bounded_action_relation_plans_session_index_not_archive_wide_tool_scan` — 1 passed.
- Anti-vacuity: same test against unmodified `action_relation.py` — fails with `SEARCH u USING INDEX idx_blocks_type_tool (block_type=?)` (the exact regression this test guards).
- `devtools test tests/unit/storage/test_archive_tiers_archive.py tests/unit/storage/test_planner_statistics_seed.py tests/unit/storage/test_delegation_facts_bulk_rebuild.py tests/unit/archive/query/test_execution_control.py` — 65 passed, 4 pre-existing failures confirmed identical on unmodified `origin/master` (unrelated to this change — tracked as `polylogue-1ldl`, a stale `>=50000 VM steps` anti-vacuity threshold in two other tests whose "archive-wide fallback" mutation stopped being expensive once PR #3018 made the `actions` view backed by the small indexed `action_pairs` table, plus a `query_units` vs `api.query_units` call-log naming mismatch in two more).
- `mypy --strict polylogue/storage/sqlite/action_relation.py tests/unit/storage/test_archive_tiers_archive.py` — clean.
- `devtools verify --quick` — exit 0, all 16 steps green.

Ref polylogue-z9gh.3, polylogue-z9gh.7
Sinity added a commit that referenced this pull request Jul 27, 2026
## Summary

Fixes two pre-existing, execution-layer-only gaps in the generic `find`/`read`
CLI query route: `near:id:<ref>` silently fell back to an unfiltered session
list instead of real vector-similarity ranking, and `lineage:id:<ref>` never
materialized its declared `parent_refs`/`child_refs`/`continuation`
recursive-graph projection columns.

## Problem

`polylogue-z9gh.3`'s 2026-07-20 note narrowed the bead's remaining scope to
two "size S" residuals, confirmed via a spot-check against a seeded demo
archive: `near:id:` executes without error via the generic find/read CLI
route but does not perform real similarity ranking (falls back to an
unfiltered session list), and the declared recursive-page projection columns
are not materialized by that same route for `lineage:id:` queries.

I independently re-verified both against a live `polylogue demo seed`
archive before writing any fix:

- `polylogue find 'near:id:<seed>' --format json` returned the exact same
  19-session list, in the same order, as a query with no filter at all.
- `polylogue find 'lineage:id:<parent>' --format json` correctly narrowed to
  the 2-session lineage family (the SQL-level filter already worked), but
  neither row carried `parent_refs`, `child_refs`, or `continuation`.

Root cause for `near:id:`: `polylogue/cli/archive_query.py`'s hand-rolled
search-execution path (`_query_hits`, `_daemon_session_page_supported`,
`_try_emit_daemon_session_page`) only ever threaded `similar_text` through;
`SessionQuerySpec.similar_session_id` was never read anywhere in that file,
so a bare `near:id:` predicate (no FTS terms, no `similar_text`) fell through
every branch straight to the plain `archive.list_summaries(**filter_kwargs)`
call. (The separate `SessionFilter`/`archive_execution.py` route already had
correct vector-seeded ranking since PR #3018 — this bug was isolated to the
CLI's own parallel execution path.)

Root cause for `lineage:id:`: the SQL-level `QueryLineagePredicate` filter
(via `boolean_predicate`) was correct, but no code anywhere translated the
declared `RECURSIVE_COLUMNS` (`session_id`, `parent_refs`, `child_refs`,
`continuation`) from `archive/query/discovery.py` into actual payload fields.

## Solution

- `polylogue/cli/archive_query.py`: thread `similar_session_id` through
  `_query_hits` the same way `similar_text` already is. When set, it calls
  the existing `VectorProvider.query_by_session` mechanism (the same
  mechanism `archive_execution.py`'s `_session_seed_scored` already uses for
  the `SessionFilter` route) rather than building new vector-search code.
  Raises a typed `click.UsageError` when no vector backend is configured or
  the seed session has no stored embeddings, matching the existing
  `near:"text"` error contract. Also excludes `similar_session_id` from the
  daemon session-page fast path (`_daemon_session_page_supported`), since
  that fast path's `/api/sessions` split-archive route has the identical gap
  and forcing local execution is the minimal fix within this file's scope.
- `polylogue/storage/sqlite/archive_tiers/archive.py`: adds
  `ArchiveStore.session_lineage_edges`, a small bounded query over the
  existing `sessions.parent_session_id` column (the same column
  `lineage:id:` already filters on via `root_session_id`) returning direct
  one-hop parent/child ids for a page of session ids — no new recursive
  graph traversal.
- `polylogue/cli/archive_query.py` + `polylogue/surfaces/payloads.py`: when a
  list page's `boolean_predicate` carries a `QueryLineagePredicate`
  (`lineage:id:`), look up per-page lineage edges and populate
  `SessionListRowPayload.parent_refs`/`child_refs`/`continuation`.
  `continuation` mirrors the page's own pagination cursor; edges are
  qualified per page, consistent with the "recursive-page" result-semantics
  contract already documented in `archive/query/discovery.py`
  (`RESULT_SEMANTICS_TEACHING`).
- Regenerated `docs/schemas/cli-output/session-list-row.schema.json`,
  `docs/openapi/search.yaml`, and `webui/src/api/generated.ts` for the two
  new payload fields.

No grammar changes: `polylogue/archive/query/expression.py` is untouched.

## Verification

- Manual, against a seeded demo archive: `near:id:<ref>` now raises a typed
  error instead of returning the full session list; `lineage:id:<ref>` now
  emits `parent_refs`/`child_refs` per row.
- `devtools test tests/unit/cli/test_query_exec_laws.py` — 88 passed (adds 3
  new tests: real vector-ranked `near:id:` through the CLI route with an
  assertion that `list_summaries` is never reached, a typed `UsageError`
  with no vector backend configured, and a real-archive `lineage:id:` test
  via `SessionBuilder`/`write_parsed_session_to_archive` proving
  `parent_refs`/`child_refs` materialize correctly against production
  `ArchiveStore` SQL, not a mock).
- `devtools test tests/unit/cli/test_archive_query.py tests/unit/cli/test_cli_output_schemas.py` — 135 passed.
- `devtools test tests/unit/archive/test_near_session_seed_execution.py tests/unit/storage/test_vec_session_seed.py` — 9 passed.
- `devtools test tests/unit/mcp/test_query_request_contracts.py tests/unit/cli/test_query_expression.py tests/unit/cli/test_select.py` — 449 passed, 1 skipped.
- `mypy` on all three changed source files — no issues.
- `ruff check` + `ruff format --check` — clean.
- `devtools render all --check` — sync OK, no "out of sync" lines.
- `devtools verify --quick` — exit 0 (also ran automatically via the pre-push hook).

Not run: `devtools verify --all`/full suite — seeding `pytest-testmon` from
scratch triggered a large, apparently pre-existing failure spread across the
whole suite baseline unrelated to these three files; the targeted
`devtools test` runs above cover every file this change touches or could
plausibly affect.

Ref polylogue-z9gh.3
Sinity added a commit that referenced this pull request Jul 27, 2026
Problem: polylogue-z9gh.3's design calls for "typed structured-plan lowering
to one AST" and OpenAPI/JSON schema generation for the query-discovery
vocabulary. explain_expression() already computes a compiled predicate tree
and per-branch ast/lowering_plan dicts, but they were hand-rolled
dict[str, object] shapes -- correct, but opaque to external tooling (an MCP
client or OpenAPI-generated SDK only ever saw an untyped dict). This was the
one named, not-yet-attempted size-M residual left on z9gh.3 after #3018,

What changed:
- New polylogue/archive/query/query_ast_schema.py: Pydantic models mirroring
  every predicate/pipeline-stage/clause dataclass's existing to_payload()
  shape one-to-one (QueryPredicateAst discriminated union, clause/ref-operand/
  pipeline projections, QueryExpressionExplanationAst). This is a validating
  projection, not a second AST -- predicate_to_ast()/explanation_payload_to_ast()
  validate the dataclasses' own to_payload() output against the schema, so a
  producer that drifts from this shape fails loudly instead of silently
  diverging. Versioned as polylogue.query-explain-ast.v1, kept distinct from
  the existing polylogue.query-definition.v1 content-hashing protocol version
  (documented in the module docstring).
- QueryExpressionExplanation.to_payload() now stamps schema_version -- the
  only new key; MCP explain(kind="query") and Polylogue.explain_query_expression()
  callers see it automatically.
- devtools/render_openapi.py: publish QueryExpressionExplanationAst (with its
  full nested $defs) in docs/openapi/search.yaml, plus an
  x-polylogue-query-ast vendor extension documenting the schema version and
  how to obtain it live (MCP explain / Polylogue.explain_query_expression()).
  No new HTTP route was added -- there is no existing daemon route for query
  explain, so publishing schemas without a bound path keeps this PR to the
  documented residual rather than growing a new live surface.
- Regenerated docs/openapi/search.yaml, webui/src/api/generated.ts (the
  typed TS client derives from it), and the topology projection/status docs
  (new module).

Verification:
- devtools test tests/unit/archive/query/test_query_ast_schema.py -- 28
  passed: predicate<->AST round trip over 11 representative predicate shapes
  (field/not/and/or/exists/sequence/fts/semantic/lineage), full
  explanation-payload validation over 13 representative DSL expressions
  (compact field query, Boolean AND/OR, near: semantic, lineage:id:, exists,
  seq(), pipeline stages sort/limit/offset, group-by-count aggregate, JSON
  spec, durable-reference pipeline, terminal unit sources), a JSON-Schema
  buildability check, and two schema-drift rejection tests.
- Ad hoc sweep of all 106 positive rows in archive/query/discovery.py's
  QUERY_DISCOVERY_EXAMPLES corpus validated cleanly against the new schema
  (0 failures) before writing the formal test file.
- devtools test tests/unit/cli/test_query_expression.py
  tests/unit/archive/query/test_predicate_payload_roundtrip.py
  tests/unit/devtools/test_render_openapi.py tests/unit/api/test_facade_contracts.py
  -- 751 passed, 1 skipped (no regressions in explain/predicate/OpenAPI
  surfaces).
- mypy --strict and ruff check/format clean on all touched files.
- devtools render all --check: sync OK on every generated surface
  (openapi, webui-client, topology-status, and the rest).
- Not run: the full non-slow suite / devtools verify --seed-testmon (stalled
  600s into an unrelated corpus after cleanly finishing this PR's own tests --
  consistent with heavy concurrent test load from other agent worktrees on
  this shared host, not a regression from this change).

Ref polylogue-z9gh.3

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

## Summary

Adds a canonical, versioned Pydantic AST schema for the query DSL's
compiled
predicate tree, unit-source pipelines, and lowering plan, and wires it
into
`devtools render openapi` so the shape is published in
`docs/openapi/search.yaml` (and the derived `webui/src/api/generated.ts`
TypeScript client).

## Problem

`polylogue-z9gh.3`'s design explicitly calls for "typed structured-plan
lowering to one AST" and OpenAPI/JSON schema generation for the query
discovery vocabulary. Most of that program already shipped (#3018,
#3066,
#3296), but the bead's own notes named exactly one residual not yet
attempted: **"structured-plan -> canonical AST lowering + OpenAPI
generation"** (sized M). `explain_expression()` already computes a
compiled
predicate tree and per-branch `ast`/`lowering_plan` dicts (see

`polylogue/archive/query/expression.py:_ast_payload`/`_lowering_plan_payload`/
`QueryExpressionExplanation.to_payload`), but they were hand-rolled
`dict[str, object]` shapes: correct, but opaque to external tooling. An
MCP
client or an OpenAPI-generated SDK only ever saw an untyped dict with no
documented schema.

## Solution

- **New `polylogue/archive/query/query_ast_schema.py`**: Pydantic models
  mirroring every existing predicate/pipeline-stage/clause dataclass's
  `to_payload()` shape one-to-one — `QueryPredicateAst` (a discriminated
  union covering field/not/and-or/exists/sequence/fts/semantic/lineage
  predicates), clause/ref-operand/pipeline-stage projections, and the
  top-level `QueryExpressionExplanationAst`. This is deliberately a
  *validating projection*, not a second AST or a parallel IR:
  `predicate_to_ast()` / `explanation_payload_to_ast()` validate the
dataclasses' own existing `to_payload()` output against the schema, so
if
  a producer's payload shape ever drifts from what's declared here, a
  Pydantic `ValidationError` surfaces immediately in the new test file
  rather than the drift silently reaching an agent or generated client.
- Versioned as `polylogue.query-explain-ast.v1`
(`QUERY_AST_SCHEMA_VERSION`), kept a **distinct axis** from the existing
  `polylogue.query-definition.v1` content-hashing protocol version in
  `polylogue/core/query_identity.py` — the module docstring explains why
they must not be conflated (one versions the content-addressed predicate
  grammar used for query hashing/identity, the other versions this new
  broader discovery/explain envelope).
- `QueryExpressionExplanation.to_payload()` now stamps `schema_version`
—
  the only new key added to the existing payload shape. MCP
`explain(kind="query")` and `Polylogue.explain_query_expression()`
callers
  pick it up automatically with no call-site changes.
- **`devtools/render_openapi.py`**: publishes
`QueryExpressionExplanationAst`
  (with its full nested `$defs` graph — every predicate/pipeline-stage
variant) as a component schema in `docs/openapi/search.yaml`, plus a new
`x-polylogue-query-ast` vendor extension documenting the schema version,
  the root schema ref, and how to obtain a live instance (there's no
  existing daemon HTTP route for query explain, only the MCP `explain`
  operation and the Python facade, so the extension says that explicitly
  rather than implying a route that doesn't exist).
- Regenerated `docs/openapi/search.yaml`, `webui/src/api/generated.ts`
(the
  typed TS client derives from the OpenAPI doc), and
`docs/plans/topology-target.yaml` / `docs/topology-status.md` (new
module
  under `polylogue/`, per this repo's topology-projection convention).

### What's covered vs. deferred

Covered: a documented, versioned, round-trip-tested AST for the
`SessionQuerySpec.boolean_predicate` tree (the actual "structured plan"
a
compiled query lowers to), the
clause/pipeline/unit-source/reference-operand
projections `explain_expression()` already emits, and OpenAPI
publication of
all of it.

Deferred (explicitly out of scope for this residual, not silently
dropped):
no new HTTP route for query-explain was added (MCP + Python facade
remain
the only live surfaces); the `unit_source.pipeline_stages`
transform-stage
vocabulary member (`QueryUnitTransformStageAst`) is modeled but has no
producer yet (matches upstream's own "reserved vocabulary member" note
on
`QueryUnitTransformStage`); this PR does not touch execution-layer gaps
(those were already handled separately in #3296).

## Verification

- `devtools test tests/unit/archive/query/test_query_ast_schema.py` — 28
passed: predicate↔AST round trip over 11 representative predicate shapes
  (field/not/and/or/exists/sequence/fts/semantic/lineage), full
  explanation-payload validation over 13 representative DSL expressions
(compact field query, Boolean AND/OR, `near:"..."` semantic,
`lineage:id:`,
`exists`, `seq(...)`, pipeline stages sort/limit/offset, group-by-count
  aggregate, raw JSON spec, durable-reference pipeline
  `from result-set:... | ...`, terminal unit sources), a JSON-Schema
  buildability check, and two schema-drift rejection tests.
- Ad hoc sweep (not part of the committed test file, but run manually
before
  writing it) of all 106 positive rows in
`archive/query/discovery.py:QUERY_DISCOVERY_EXAMPLES` validated cleanly
  against the new schema with 0 failures.
- `devtools test tests/unit/cli/test_query_expression.py
  tests/unit/archive/query/test_predicate_payload_roundtrip.py
  tests/unit/devtools/test_render_openapi.py
  tests/unit/api/test_facade_contracts.py` — 751 passed, 1 skipped (no
  regressions in the explain/predicate/OpenAPI surfaces touched by this
  change).
- `mypy --strict` and `ruff check`/`format` clean on all touched files.
- `devtools render all --check` — sync OK on every generated surface
  (openapi, webui-client, topology-status, and the rest).
- Not run: the full non-slow test suite / `devtools verify
--seed-testmon`
  (it stalled 600s into an unrelated part of the corpus, after cleanly
  finishing every test in this PR's own file — consistent with heavy
concurrent test load from other agent worktrees sharing this host at the
  time, not a regression introduced here). The pre-push hook's
`devtools verify --quick` (format + lint + mypy + render-all-check) ran
  and passed on push.

Ref polylogue-z9gh.3


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

## Summary by CodeRabbit

* **New Features**
* Added a versioned, canonical schema for query explanations and
compiled query ASTs.
* Query explanations now include a schema version and validated
predicate, pipeline, and lowering-plan details.
* Published the query AST schema through the OpenAPI specification for
external tooling.
* Added generated TypeScript types for query AST and pipeline
structures.

* **Documentation**
* Documented how to obtain query AST explanations and the schema’s
supported structures.

* **Tests**
* Added coverage for AST round trips, schema validation, serialization,
and rejection of invalid data.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: Claude <[email protected]>
Sinity added a commit that referenced this pull request Jul 27, 2026
… mutation canaries (#3341)

## Summary

Fixes a stale VM-step anti-vacuity mutation in two archive query tests
(polylogue-1ldl) and verifies a previously-stale live-batch assertion
(polylogue-5202) is already resolved on master by an unrelated prior PR.

## Problem

**polylogue-1ldl**:
`test_exact_session_action_count_bounds_pairing_before_global_ranking`
(tests/unit/storage/test_archive_tiers_archive.py) and
`test_exact_session_multi_aggregate_work_is_not_amplified_by_irrelevant_growth`
(tests/unit/archive/query/test_execution_control.py) each monkeypatch
`_action_relation_for_query` to fall back to the plain `"actions"`
relation name, simulating pre-z9gh.2 "global-first" behavior, and assert
the resulting query costs `>= 50000` SQLite VM steps as an anti-vacuity
control. Since PR #3018 (z9gh.2) replaced the old windowed-CTE `actions`
compatibility view with one backed by the small, pre-materialized,
session_id-indexed `action_pairs` table, renaming the relation to
`"actions"` no longer forces any meaningfully different/expensive path —
both tests measured 0/400 VM steps for the "mutant" query, well under
the 50000 threshold. The canary had silently stopped discriminating the
exact regression it exists to catch.

**polylogue-5202**:
`test_live_multi_session_divergence_reopens_raw_authority`
(tests/unit/sources/test_live_batch_support.py) was reported failing
with a stale `failed == [second]` assertion predating PR #3129's
deferred-membership semantics change. Investigation found the assertions
were already updated to the current-correct `failed == [] / succeeded ==
[second]` shape by PR #3282 (commit 4120c40, merged 2026-07-26, Ref
polylogue-6mvg) as part of unrelated FTS-repair-deferral work. The test
already passes on current master with no further code change needed.

## Solution

- Replaced the now-inert `lambda **_kwargs: ("", "actions", [])`
mutation at both polylogue-1ldl sites with one that forces the
actually-expensive "global-first" branch that still exists in
`action_relation_select_sql(session_placeholders=None)` — the unbounded
windowed tool_use/tool_result pairing recomputation across every block
in the archive, instead of a read against the materialized
`action_pairs` table. Verified this reproduces genuinely archive-wide
cost (measured 53500 VM steps for the count-only path vs 400 bounded).
- Added inline comments at both mutation sites recording what changed
(#3018) and why the old mutation stopped discriminating.
- No code change for polylogue-5202 — verified its test and the broader
`raw_materialization`/`raw_authority` selection are green on master, and
closing the bead by reference to PR #3282.
- Filed polylogue-0twa for an unrelated, pre-existing stale
`query_units` vs `api.query_units` call-log naming assertion noticed in
the same test file (out of scope for this PR).

## Verification

- `devtools test tests/unit/storage/test_archive_tiers_archive.py
tests/unit/archive/query/test_execution_control.py` → 60 passed, 2
failed (pre-existing, out-of-scope polylogue-0twa naming mismatch; both
polylogue-1ldl tests pass)
- `devtools test -k "raw_materialization or raw_authority"` → 198 passed
(includes polylogue-5202's test)
- `ruff check` / `ruff format --check` on both changed files → clean
- `mypy --strict` on both changed files → no issues
- `devtools render all --check` → no drift
- pre-push `devtools verify --quick` → all steps ok

Ref polylogue-1ldl, polylogue-5202

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 added a commit that referenced this pull request Jul 29, 2026
…for PolylogueInsightsMixin

1. tests/unit/core/test_paths.py::
   TestPathsPublicBoundary::test_paths_root_exports_only_directory_layout_symbols:
   `browser_capture_pairing_state_path` is a real public symbol in
   polylogue/paths.py (sibling of browser_capture_receiver_identity_path/
   browser_capture_receiver_token_path) that was never added to this
   test's frozen `__all__` allowlist.

2. tests/unit/core/test_sync_surface_runtime.py::
   test_polylogue_products_mixin_forwards_all_product_calls needed a
   3-part fix after #3018 (2026-07-17, "bound agent-facing archive
   reads") changed how `PolylogueInsightsMixin` reads the archive,
   pre-existing and never caught since (per-PR CI skips the heavy suite):
   - `polylogue.api.insights` only imports `ArchiveStore` under
     `TYPE_CHECKING` now; the runtime call site does a local import from
     its real home (`polylogue.storage.sqlite.archive_tiers.archive`), so
     that's what `patch(...)` must target -- patching the dotted path
     the test used raised `AttributeError` before ever reaching the
     method under test.
   - `execute_archive_read`'s worker-thread runner
     (archive/query/execution_control.py::InterruptibleSQLiteRead.run)
     calls `ArchiveStore.open_existing(...)` directly and uses the
     return value as the store (manual `finally`-block cleanup, no
     `with` statement) -- not the old
     `with ArchiveStore.open_existing(...) as store:` pattern the mock
     was built for (`.return_value.__enter__.return_value`). The store
     mock now sets `MagicMock(return_value=archive)` directly.
   - `list_tool_usage_insights` genuinely forwards to
     `archive.list_tool_usage_insights(query)` (confirmed by reading
     polylogue/api/insights.py:521-534); the test's mock return value
     (`["tool-usage"]`, a bare string) didn't match the real
     `ToolUsageInsight` model's shape the assertion
     (`tool_usage[0].insight_kind == "tool_usage"`) expects, and the
     final `archive.list_tool_usage_insights.assert_not_called()` simply
     contradicted the call the code demonstrably makes. Built a real
     `ToolUsageInsight(provenance=ArchiveInsightProvenance(...))` for the
     mock and changed the assertion to `assert_called_once()`.

Verification: devtools test tests/unit/core/test_paths.py
tests/unit/core/test_sync_surface_runtime.py -- 20 + 4 passed (was 2
failed). mypy --strict and ruff check/format clean.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0182HDxDpJpsbn2qcKWK6Fsf
@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.

  • 68.F023 / P1: fixed-already at the checked revision: polylogue/operations/session_reads.py:63 reconstructs the resumed request with the continuation-bound page size and offset before execution. The next token advances that same transaction offset at lines 99-101, so the current MCP session-search owner no longer fetches page one and filters it using a later cursor.

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