Skip to content

feat(query): expose context snapshots as terminal rows - #2112

Merged
Sinity merged 3 commits into
masterfrom
feature/feat/context-snapshot-query-unit-2006
Jun 18, 2026
Merged

Sinity merged 3 commits into
masterfrom
feature/feat/context-snapshot-query-unit-2006

Conversation

@Sinity

@Sinity Sinity commented Jun 18, 2026 •

Copy link
Copy Markdown
Owner

Summary

This PR extends the terminal query-unit surface with context-snapshots where ... rows and projects review-injected recovery events into concrete context snapshots. It also rounds out terminal query-unit rendering for assertion/observed-event/context-snapshot rows and keeps explicit terminal-unit expressions on query-unit routing instead of root stats routing.

Ref #2006
Ref #1882

Problem

The query DSL and terminal row substrate could address messages, actions, blocks, assertions, and observed events, but context snapshots were still trapped inside recovery projections/work-packet rendering. Review-injected context was represented as an observed event but not as a context boundary that API/CLI/MCP/daemon callers could query. While wiring this, _summary_field_matches() also had a fail-open fallback for scoped session fields on runtime-transform units, so supported-but-unimplemented predicates such as session.tool:bash could silently broaden observed-event/context-snapshot results.

Solution

  • Add context-snapshot to terminal unit parsing, metadata, payload schemas, generated OpenAPI/CLI schema docs, and daemon/API/MCP error text.
  • Execute context-snapshots where ... by compiling recovery digests and returning typed ContextSnapshotQueryRowPayload rows.
  • Project review_injected_context recovery events into ContextSnapshot(boundary="review_injection", inheritance_mode="injected") rows with event/object refs as segments.
  • Render assertion, observed-event, and context-snapshot terminal rows in CLI plaintext and JSON envelopes.
  • Make root stats detection short-circuit when query terms are present so terminal unit expressions route to the terminal executor.
  • Make runtime-transform scoped session fields fail closed unless the in-memory summary can actually evaluate them.

Intentional scope note: this branch absorbed the terminal-query rendering/routing pieces that overlap with #1883, but not #1883's assertion lifecycle/defaults work. That is prepared separately on feature/feat/assertion-defaults-1883.

Verification

  • nix develop --command devtools test tests/unit/insights/test_transforms.py::test_review_delivery_events_are_extracted_and_projected tests/unit/insights/test_transforms.py::test_review_injection_context_snapshot_reaches_work_packet tests/unit/api/test_facade_contracts.py::test_query_units_returns_context_snapshot_rows tests/unit/cli/test_query_expression.py::TestBooleanQueryExpression::test_terminal_context_snapshot_source_returns_runtime_rows tests/unit/cli/test_query_exec_laws.py::TestSearchQueryContracts::test_assertion_unit_source_returns_json_envelope tests/unit/cli/test_query_exec_laws.py::TestSearchQueryContracts::test_assertion_unit_source_renders_plain_rows tests/unit/cli/test_query_exec_laws.py::TestSearchQueryContracts::test_context_snapshot_unit_source_routes_to_query_units tests/unit/daemon/test_web_reader.py::TestReaderQueryUnits::test_query_units_endpoint_returns_terminal_assertion_rows tests/unit/daemon/test_web_reader.py::TestReaderQueryUnits::test_query_units_endpoint_returns_context_snapshot_rows tests/unit/daemon/test_web_reader.py::TestReaderQueryUnits::test_query_units_endpoint_rejects_session_expression tests/unit/mcp/test_server_surfaces.py::TestArchiveGenericToolSurfaces::test_query_unit_payload_returns_assertion_rows tests/unit/mcp/test_server_surfaces.py::TestArchiveGenericToolSurfaces::test_query_units_tool_returns_context_snapshot_rows_without_archive_operations tests/unit/mcp/test_server_surfaces.py::TestArchiveGenericToolSurfaces::test_query_units_tool_rejects_session_expression -> 13 passed.
  • nix develop --command devtools verify --quick -> exit_code 0.
  • Pre-push quick gate -> exit_code 0.
  • nix develop --command devtools verify -> static/generated checks passed, then pytest-testmon selected 11,357 tests and timed out at the 2700s harness limit while still progressing at 91%; no test failure report was produced. Postmortem diagnosis: pytest_timeout, peak tree RSS ~2.8 GiB, /dev/shm remained small.

Summary by CodeRabbit

Release Notes

  • New Features

    • Added support for querying context snapshots alongside messages, actions, blocks, assertions, and observed-events. Users can now filter and retrieve context-snapshot terminal rows using the context-snapshots where ... query syntax.
  • Documentation

    • Updated API documentation, CLI schemas, and guides to reflect context-snapshot query capabilities and available filter fields.
  • Tests

    • Added comprehensive test coverage for context-snapshot query functionality across API, CLI, and integration layers.

Problem
#2006 made terminal query units the shared row-level query surface, but context snapshots were still only visible inside recovery projections and work-packet rendering. Runtime-transform units also accepted scoped session predicates that the in-memory summary matcher could not evaluate, which could silently broaden observed-event and context-snapshot results.

What changed
- Project review-injected recovery events into concrete ContextSnapshot rows.
- Add context-snapshot terminal query-unit parsing, payloads, CLI rendering, API/MCP/daemon wiring, and generated docs/schemas.
- Keep terminal unit expressions on query-unit routing instead of stats routing.
- Make runtime-transform scoped session predicates fail closed for unsupported summary fields.

Verification
- devtools test focused 13-node query-unit/context-snapshot surface set: 13 passed.
- devtools verify --quick: exit_code 0.

Ref #2006
Ref #1882
@coderabbitai

coderabbitai Bot commented Jun 18, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

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

More reviews will be available in 21 minutes and 23 seconds. Learn how PR review limits work.

Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file).

⌛ How to resolve this issue?

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

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

🚦 How do rate limits work?

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

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, the refill rate gradually slows as usage increases. The highest same-day bursts are limited more strictly.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: c73809e9-6dcd-46eb-8e1c-aa9ba75aded8

📥 Commits

Reviewing files that changed from the base of the PR and between 1ea198e and f339ccb.

📒 Files selected for processing (4)
  • docs/search.md
  • polylogue/archive/query/metadata.py
  • polylogue/archive/query/unit_results.py
  • tests/unit/cli/test_query_expression.py
📝 Walkthrough

Walkthrough

Adds context-snapshot as a new terminal query-unit type across the full stack. A new ContextSnapshotQueryRowPayload model is introduced, wired through the query DSL metadata, expression parsing/lowering, archive execution engine, CLI renderers, and HTTP/MCP/API error messages. Run projection gains a "review_injection" boundary. Published JSON Schema, OpenAPI spec, and documentation are updated accordingly, with comprehensive new tests at every layer.

Changes

context-snapshot query unit

Layer / File(s) Summary
Surface payload contract
polylogue/surfaces/payloads.py
Adds ContextSnapshotQueryRowPayload model, extends QueryUnitKind with "context-snapshot", adds the new class to QueryUnitRowPayload union and __all__.
Query metadata: structural fields and unit registry
polylogue/archive/query/metadata.py
Extends QueryUnitName literal, adds _CONTEXT_SNAPSHOT_STRUCTURAL_FIELDS and _CONTEXT_SNAPSHOT_STRUCTURAL_FIELD_INFO, registers the unit in STRUCTURAL_QUERY_UNIT_REGISTRY via _context_snapshot_field_infos().
Expression DSL: parsing, validation, and lowering
polylogue/archive/query/expression.py
Adds context-snapshot to predicate validation, unit-source recognition, _parse_source_where_predicate (returns None like observed-event), and explain_expression terminal-unit lowering (suppresses compatibility_selector).
Run projection: review_injection ContextSnapshot
polylogue/insights/run_projection.py
Extends ContextBoundary with "review_injection" and emits an injected ContextSnapshot in build_run_projection when event.kind == "review_injected_context".
Archive query execution pipeline
polylogue/archive/query/unit_results.py
Adds context-snapshot filtering/serialization/pagination (_query_context_snapshots), updates _summary_field_matches semantics, and dispatches source.unit == "context-snapshot" in query_unit_rows.
CLI text renderers and stats guard
polylogue/cli/archive_query.py, polylogue/cli/root_request.py
Extends _emit_unit_source_rows to cover assertion, observed-event, and context-snapshot with dedicated formatter helpers; refactors should_show_stats to early-return on query_terms.
Error message alignment
polylogue/api/archive.py, polylogue/daemon/http.py, polylogue/mcp/archive_support.py
Updates ExpressionCompileError and HTTP error strings to reference observed-events/context-snapshots alongside existing unit names.
Published schemas and OpenAPI spec
docs/openapi/search.yaml, docs/schemas/cli-output/query-unit-envelope.schema.json, devtools/render_cli_output_schemas.py, devtools/render_openapi.py
Adds ContextSnapshotQueryRowPayload to both specs, extends QueryUnitEnvelope unit enum and anyOf, and registers new CLI surface strings.
Documentation
docs/search.md, docs/daemon.md, docs/cli-reference.md, docs/schemas/cli-output/README.md
Updates grammar examples, endpoint descriptions, and terminal-unit-query reference sections to include assertions, observed-events, and context-snapshots.
Run projection tests
tests/unit/insights/test_transforms.py
Extends review-delivery projection test for review_injection snapshot fields; adds test_review_injection_context_snapshot_reaches_work_packet.
Expression DSL and query execution tests
tests/unit/cli/test_query_expression.py
Adds parsing/lowering test for context-snapshots source expression and runtime rows test covering session_start, review_injection, and unsupported filter paths.
CLI query execution tests
tests/unit/cli/test_query_exec_laws.py
Seeds user.db in fixture; adds three contract tests for JSON-envelope assertions, plain-text assertion rendering, and context-snapshot routing.
API facade, daemon, and MCP tests
tests/unit/api/test_facade_contracts.py, tests/unit/daemon/test_web_reader.py, tests/unit/mcp/test_server_surfaces.py
Adds facade context-snapshot envelope test; updates daemon assertion-row test with explicit DB bootstrap; adds MCP assertion payload and context-snapshot tool tests.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • Sinity/polylogue#2049: Extends the same polylogue/archive/query/expression.py and polylogue/cli/archive_query.py terminal unit-source execution path that this PR builds upon for context-snapshot.
  • Sinity/polylogue#2093: Modifies the same polylogue/archive/query/metadata.py structural-query field/unit registry layer where this PR registers the new context-snapshot unit.

Suggested labels

area:cli, area:storage, area:schema, area:parser, type:test

Poem

🐇 Hop, hop! A new snapshot in view,
context-snapshot rows now come through.
Boundaries injected, inheritance set,
The query-unit envelope's best yet.
From archive to CLI, the rabbit bounds free—
review_injection captured for thee! 🌿

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 26.79% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title "feat(query): expose context snapshots as terminal rows" directly and clearly summarizes the primary change—adding context snapshots as queryable terminal rows—which aligns with the PR's core objective.
Description check ✅ Passed The PR description comprehensively follows the template with all required sections: Summary (1-3 sentences explaining the change), Problem (why context snapshots were trapped), Solution (how they're now exposed), Verification (specific test commands with passing results), and Risks/Follow-ups (scope notes on deferred assertion work).
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/feat/context-snapshot-query-unit-2006

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 and usage tips.

github-actions Bot pushed a commit that referenced this pull request Jun 18, 2026

@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: 1ea198e57f

ℹ️ 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/archive/query/unit_results.py Resolved
Comment thread polylogue/archive/query/unit_results.py Resolved

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@docs/search.md`:
- Around line 7-8: The documentation contains an inconsistency where lines 7-8
mention `assertions/observed-events/context-snapshots` as valid unit-source
forms alongside `messages/actions/blocks`, but the canonical grammar rule for
`unit-query` on line 36 only includes `messages/actions/blocks`. Update the
`unit-query` grammar rule definition to include all the unit sources that are
documented in the earlier section, specifically expanding it to cover
`sessions/messages/actions/blocks/assertions/observed-events/context-snapshots`
so the grammar matches the documented behavior.

In `@polylogue/archive/query/unit_results.py`:
- Around line 314-327: The archive.list_summaries call on line 314 has a
hardcoded limit of 1_000_000 summaries which silently truncates results in large
archives without attempting to fetch remaining summaries. Remove the fixed limit
parameter from the archive.list_summaries call and implement pagination logic to
iteratively fetch all summaries in batches until all results are consumed. This
ensures complete result sets are returned instead of silently truncating at an
arbitrary threshold.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 546dd551-36b2-48a3-8f22-a92a5ac445f3

📥 Commits

Reviewing files that changed from the base of the PR and between 4b41f13 and 1ea198e.

📒 Files selected for processing (24)
  • devtools/render_cli_output_schemas.py
  • devtools/render_openapi.py
  • docs/cli-reference.md
  • docs/daemon.md
  • docs/openapi/search.yaml
  • docs/schemas/cli-output/README.md
  • docs/schemas/cli-output/query-unit-envelope.schema.json
  • docs/search.md
  • polylogue/api/archive.py
  • polylogue/archive/query/expression.py
  • polylogue/archive/query/metadata.py
  • polylogue/archive/query/unit_results.py
  • polylogue/cli/archive_query.py
  • polylogue/cli/root_request.py
  • polylogue/daemon/http.py
  • polylogue/insights/run_projection.py
  • polylogue/mcp/archive_support.py
  • polylogue/surfaces/payloads.py
  • tests/unit/api/test_facade_contracts.py
  • tests/unit/cli/test_query_exec_laws.py
  • tests/unit/cli/test_query_expression.py
  • tests/unit/daemon/test_web_reader.py
  • tests/unit/insights/test_transforms.py
  • tests/unit/mcp/test_server_surfaces.py

Comment thread docs/search.md Resolved
Comment thread polylogue/archive/query/unit_results.py Resolved
Sinity added 2 commits June 18, 2026 19:18
Problem: review found runtime-transform unit queries treated session.path as cwd and evaluated session.since only against updated_at, diverging from normal session filter semantics.\n\nWhat changed: session.path now fails closed on runtime-transform summaries instead of aliasing to cwd, session.since/until use updated_at with created_at fallback, and completions no longer teach session.path for terminal structural units.\n\nVerification: devtools test tests/unit/cli/test_query_expression.py (249 passed); devtools verify --quick (exit 0).\n\nRef #2006
Problem: runtime-transform terminal query units scanned session summaries with a fixed million-row cap, and the DSL docs still described only the original three terminal units. Code review correctly flagged both as stale behavior/documentation for #2006.

What changed: query-unit execution now pages through ArchiveStore.list_summaries for context snapshots and observed events, the search grammar documents assertion/observed-event/context-snapshot units, and focused coverage proves pagination reaches later summary pages.

Verification: nix develop --command bash -c 'devtools render-pages >/tmp/plg-2112-render-pages.log 2>&1 && ruff format polylogue/archive/query/unit_results.py polylogue/archive/query/metadata.py tests/unit/cli/test_query_expression.py && ruff check polylogue/archive/query/unit_results.py polylogue/archive/query/metadata.py tests/unit/cli/test_query_expression.py && devtools test tests/unit/cli/test_query_expression.py && devtools verify --quick'
@Sinity

Sinity commented Jun 18, 2026

Copy link
Copy Markdown
Owner Author

Addressed the latest review findings in f339ccb: docs/search.md now includes assertion, observed-event, and context-snapshot unit sources in the grammar; runtime-transform unit scans now page through ArchiveStore.list_summaries instead of using a fixed cap; the earlier session.path/session.since findings remain covered by the prior fix commit and focused tests.

github-actions Bot pushed a commit that referenced this pull request Jun 18, 2026
@Sinity
Sinity merged commit 7934d5f into master Jun 18, 2026
14 checks passed
@Sinity
Sinity deleted the feature/feat/context-snapshot-query-unit-2006 branch June 18, 2026 17:37
@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.

  • 59.F088 / P2: fixed-already at the checked revision: polylogue/storage/sqlite/archive_tiers/archive_query_reads.py:1486-1489 distinguishes referenced_paths from cwd_prefix. Materialized context-snapshot and observed-event predicates use this same lowerer, so session.path no longer aliases the working directory.
  • 59.F089 / P2: fixed-already at the checked revision: polylogue/storage/sqlite/archive_tiers/archive_query_reads.py:2741 applies since through COALESCE(updated_at_ms, created_at_ms). The materialized terminal routes delegate owning-session date filters to this shared lowerer, preserving sessions whose updated timestamp is null.

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