Skip to content

feat(query): implement the full query DSL substrate #2006

Closed

Description

@Sinity

Purpose

Implement Polylogue's full query DSL as one typed grammar, AST, metadata, and lowering pipeline over the existing archive engines. The Lark grammar in polylogue/archive/query/expression.py is the query language; compact field/text clauses and explicit Boolean predicates are entry shapes in that same grammar, not a "floor" language plus a separate future language.

This is a base product feature. Polylogue is an evidence cockpit; if users and agents cannot ask precise questions about sessions, messages, blocks, tools, actions, runs, reviews, assertions, lineage, and bundles, every higher-level view becomes a one-off report.

Current implementation reality

The current implementation is real code and should be extended in place, not bypassed:

  • polylogue/archive/query/expression.py owns the Lark grammar, field registry, structural unit registry, typed parser errors, AST/explain output, and the historical compile_expression public entrypoint. compile_expression is only a compatibility function name used by existing CLI/MCP/API callsites; it is not a separate compiler, grammar, or execution path. Its body must delegate to the canonical Lark parser, typed AST, and lowerer.
  • polylogue/archive/query/spec.py defines SessionQuerySpec, query planning, and the shared query selection contract used by current read surfaces.
  • polylogue/archive/query/predicate.py carries the typed Boolean/structural/semantic/sequence predicate nodes that are already lowerable where supported.
  • polylogue/storage/repository/archive/queries.py and storage search providers lower supported predicates into SQLite, FTS, vector, recursive traversal, and EXISTS legs.
  • polylogue/cli/query_group.py, polylogue/cli/archive_query.py, polylogue/cli/query.py, MCP, and API paths wrap the shared grammar/AST/lowerer rather than owning separate query semantics.
  • polylogue/cli/shell_completion_values.py consumes EXPRESSION_FIELD_REGISTRY and structural query-unit metadata for completion/query-builder candidates.

Current executable behavior includes:

  • compact field/text clauses such as repo:polylogue tag:active "json envelope";
  • in-field alternatives such as origin:(codex-session|claude-code-session);
  • negated field/text clauses such as -tag:stale and -"bad phrase";
  • count comparisons for messages and words;
  • explicit Boolean predicates such as sessions where (repo:polylogue OR origin:chatgpt-export) AND NOT tag:stale;
  • cross-field Boolean AND/OR/NOT over supported SQL-backed session fields;
  • FTS predicates and semantic predicates with typed rank semantics where available;
  • exists message(...), exists action(...), exists block(...), and exists assertion(...) structural predicates lowered through concrete lowerers;
  • terminal row-producing messages/actions/blocks/assertions/runs/observed-events/context-snapshots where ... queries shared by CLI JSON output, Python API, MCP, daemon HTTP, schemas, docs, and completions;
  • a sort by time [asc|desc] pipeline stage for SQL-backed terminal rows (messages, actions, blocks, assertions), with runtime-transform terminal units rejecting sort until they have durable lowerers;
  • runtime-transform terminal rows for runs, observed events, and context snapshots lowered through the recovery/run projection, with unsupported scoped session fields failing closed rather than broadening results; these runtime-transform units are terminal row sources and must not be lowered into exists run(...), exists observed-event(...), or exists context-snapshot(...) session selectors until a real durable lowerer exists;
  • lineage:id:<session> traversal through existing topology data;
  • seq(action:... -> action:...) sequence predicates over supported action evidence.

Unsupported constructs must fail typed and narrow. They must never silently broaden into full-text search.

Design principle

Do not build a database engine. Build a typed surface and lowering pipeline over engines Polylogue already has:

  • SQLite WHERE predicates and joins;
  • FTS5 for lexical search;
  • sqlite-vec / vector providers for semantic legs;
  • recursive CTEs for lineage/topology traversal;
  • EXISTS subqueries for message/block/action predicates;
  • ordinary CTE chains for pipeline stages and aggregation;
  • existing read/transform/action contracts for terminal outputs.

Every supported DSL construct must lower to one of those concrete mechanisms or to an explicit existing transform/action. Unsupported constructs must fail typed and narrow, never broaden into a looser full-text search.

Query units

The DSL should ultimately be able to name and traverse these units as implementation reaches the corresponding substrate:

  • sessions
  • messages
  • blocks
  • actions / tool calls / tool results
  • runs
  • observed-events
  • assertions
  • context-snapshots
  • bundles
  • lineage
  • files / affected paths
  • external work refs: GitHub issues, PRs, reviews, check runs, commits, branches

Units should be added with real lowerers and fixtures, not as parser-only vocabulary. messages, blocks, actions, assertions, runs, observed-events, and context-snapshots are already executable terminal row sources; messages/blocks/actions/assertions also support session-selector structural predicates where their SQL-backed substrate allows it. runs/observed-events/context-snapshots are runtime-transform terminal sources only today, so session selector surfaces must reject them with typed errors rather than manufacture unexecutable exists ... predicates. Future units such as bundles, files, external refs, phases, threads, and spans may appear only as unsupported metadata with a typed error until they have real lowerers.

Predicate AST

The predicate AST should represent both today's supported query strings and the target language:

And(children)
Or(children)
Not(child)
Leaf(unit, field, op, value)
Fts(unit, query, mode)
Semantic(unit, text_or_ref, provider/lane)
Exists(unit, predicate)
Relational(relation, source_unit, target_unit, predicate)
Sequence(ordered_steps)
Lineage(seed, relation/depth)

Operators should include equality/inclusion, negation, comparison, range, contains/FTS, semantic-near, existence, and sequence predicates where supported by the unit.

Pipeline AST

The next major ceiling is a pipeline AST for unit-changing and report-producing queries:

Source(unit, predicate?)
Filter(predicate)
Traverse(relation, target_unit)
Transform(name, args)
Aggregate(grouping, metrics)
Sort(keys)
Limit(n)
Terminal(action_or_view)

The current find QUERY then ACTION syntax should lower to Source(sessions) -> Filter(...) -> Terminal(action) through the canonical AST rather than special-casing terminal actions outside the query substrate.

Surface syntax

Preserve current query strings as canonical grammar inputs:

repo:polylogue tag:active -origin:codex "json envelope"
near:id:<session-id>
messages:>=5 words:<=2000
sessions where (repo:polylogue OR repo:sinex) AND NOT tag:stale
exists block(type:code AND text:timeout)

Add explicit power syntax for full queries. Exact parser details may evolve, but these capabilities must be expressible and tested:

sessions where words > 500 and messages between 5 and 20
messages where role:assistant and tool:bash and ~"timeout"
sessions where exists message(role:assistant and tool:bash and ~"timeout")
sessions where seq(action:file_edit -> test:fail -> action:file_edit)
session:<id> | lineage | read --view transcript
sessions where repo:polylogue | messages where tool:bash | group by tool | count
runs where issue:1840 | observed-events where kind:review_posted | read --view forensic
assertions where scope:repo:polylogue and kind:lesson and ~"query compiler"
runs where review_posted before pr_merged and not review_seen_by_tool | bundle work_packet

The syntax should be documented as a real grammar, not inferred from examples.

Parser tooling

Use Lark for the surface grammar unless implementation evidence proves a better fit. Lark is already in use here; it supports readable EBNF-style grammar, recursive/nested Boolean expressions, precedence, quoted strings, parse trees transformed into typed AST nodes, and grammar-derived metadata for docs/completion/query builders.

Do not build new DSL features as ad hoc string splitting around compile_expression, and do not introduce a separate legacy grammar concept. The Lark grammar should keep owning precedence, grouping, quoted strings, paths, literals, pipeline separators, and structured diagnostics while lowerers expand. A Pratt parser is acceptable only if a PR demonstrates that it keeps the grammar easier to maintain than Lark and still emits the same typed errors and metadata needed by docs/completion surfaces.

Recently landed slices

These landed slices should be treated as baseline. Future work should extend the same Lark/AST/lowering path instead of adding side parsers or command-local ordering rules.

Remaining implementation program

This issue is one coherent implementation program. Do not split it into conceptual micro-issues. Use multiple PRs if needed for reviewability, but each PR should land a complete working layer with tests and no orphan parser vocabulary.

Useful remaining PR boundaries:

  1. Extend comparison/range operators beyond count and date clauses for the remaining SQL-backed session fields.
  2. Extend the existing terminal-source/filter path beyond the shipped messages/actions/blocks/assertions/runs/observed-events/context-snapshots where ... units only when the owning substrate can return real rows.
  3. Add sequence predicates for realistic edit -> test fail -> edit and review/check workflows.
  4. Add pipeline stages for traversal, aggregation, sort/limit, and terminal read/analyze/bundle actions.
  5. Add bundle/file/external-ref/phase/thread/span units only where the owning substrate is ready enough to execute real rows.
  6. Keep completion/MCP/web query-builder metadata sourced from the same AST/field/unit registries.
  7. Keep runtime-transform units covered across CLI, Python API, MCP, daemon, docs, generated schemas, and completions whenever fields or projection semantics change.

These are implementation boundaries, not excuses to leave the issue as a sketch. Each merged phase should make new useful queries execute.

Required lowerers

The implementation is complete only when the DSL has lowerers for representative useful classes, not merely parser nodes:

  1. Current supported session query strings lower through the canonical Lark-backed compiler with behavior equivalent to current releases or stricter typed errors.
  2. Cross-field Boolean over SQL-backed session fields lowers to SQL predicates.
  3. FTS and semantic legs lower to existing search/vector paths with explicit rank semantics.
  4. Message/action/block predicates lower to EXISTS subqueries over messages, blocks, and action/tool rows.
  5. Sequence predicates lower over ordered action/message/event evidence.
  6. Lineage/topology traversal lowers through existing topology/logical-session data, using recursive CTEs where needed.
  7. Assertion predicates lower through the assertion substrate; run/event/context-snapshot terminal rows lower through the recovery/run projection.
  8. Bundle/file/external-ref/phase/thread/span units lower through concrete owning substrates before they become accepted grammar.
  9. Terminal actions lower through existing read/analyze/mark/delete/bundle/action contracts, not bespoke handlers.

Explainability

Every parsed query should be explainable in machine-readable form:

  • original source text;
  • parsed AST;
  • selected unit(s);
  • lowering plan;
  • execution legs: SQL, FTS, vector, recursive traversal, runtime transform;
  • unsupported/degraded nodes with typed codes;
  • estimated or observed result cardinality where available.

This is required for debugging, completion, MCP, web query builders, and safe agent use.

Error semantics

Typed errors are part of the contract. At minimum:

  • unknown unit;
  • unknown field for unit;
  • unsupported operator for field;
  • unsupported relation/traversal;
  • unsupported Boolean lowerer;
  • unsupported structural predicate;
  • unsupported terminal action for selected unit;
  • malformed syntax;
  • ambiguous bare term;
  • semantic/vector unavailable;
  • query would broaden due unsupported construct.

No unsupported syntax may silently become a broad FTS query.

Cross-surface contract

The parser, AST, lowerers, explain output, and typed errors are shared substrate. CLI, MCP, Python API, daemon/web API, completion, and future web query builder must consume the same implementation or a mechanically proven equivalent wrapper.

Surface-specific transport envelopes are allowed. Surface-specific query semantics are not.

Acceptance criteria

  • Current query strings still compile and execute with equivalent behavior or explicitly documented stricter errors.
  • The full DSL has a typed AST and shared parser/lowerer registry.
  • --explain or equivalent API returns AST and lowering details.
  • Cross-field Boolean queries over supported fields execute correctly.
  • Message/action/block predicates execute against fixture archives.
  • At least one sequence predicate over coding-agent work executes against a fixture.
  • At least one lineage/topology traversal executes against a fixture.
  • At least one review/check/run/event query supports the Fold agent workflow events into recovery/work views #1840 missed-review semantics once those events exist.
  • At least one assertion query can find evidence-linked lessons/decisions/blockers once Unify user overlays as evidence-linked assertions #1883 surfaces them.
  • Pipeline terminal actions can feed existing read, analyze, and Bundle/work-packet outputs without bespoke duplicate handlers.
  • CLI, MCP, daemon/API, Python, and completion use the same grammar metadata for representative queries.
  • Unsupported forms fail with typed errors and never broaden results.
  • Docs include a real grammar, unit/field/operator tables, examples, and unsupported-form semantics.

Tests and fixtures

Required fixture coverage:

  • current supported query parity;
  • Boolean grouping;
  • bad-field/bad-operator/bad-unit typed errors;
  • SQL-backed comparisons/ranges;
  • FTS plus structured filters;
  • vector/semantic unavailable and available paths;
  • message/action/block EXISTS predicates;
  • edit -> test fail -> edit sequence;
  • lineage traversal over continuation/subagent topology;
  • assertion query over note/decision/blocker fixtures;
  • review posted vs seen/injected/acted-on fixture once Fold agent workflow events into recovery/work views #1840 events exist;
  • cross-surface parity for at least CLI, MCP, daemon/API, and Python API.

Non-goals

  • Do not expose raw SQL.
  • Do not build a custom database engine.
  • Do not add parser-only vocabulary without execution and tests.
  • Do not create MCP/Python/web-only query features.
  • Do not replace raw archive evidence or read-model contracts.
  • Do not use LLM natural-language query as the canonical parser; NL may target this AST later.
  • Do not keep the future DSL hidden in docs/plans without issue ownership.
  • Do not keep any flat-expression compiler, fallback parser, or alternate grammar beside the Lark AST path. compile_expression may remain only as a compatibility function name for the canonical parser/AST/lowerer while existing callsites are migrated; it must not imply a behavior split.

Related issues

Forensic audit reinforcement: QueryUnitDescriptor is a closure gate

The 2026-06-19 static audit found that the remaining query problem is not parser availability. The Lark grammar is already real. The residual risk is metadata scatter: adding or changing a terminal unit currently requires edits across query metadata, parser validation, terminal execution, row filtering, payload schemas, CLI rendering, daemon/API/MCP wrappers, completions, docs, and tests.

Before this issue is closed, either implement a shared QueryUnitDescriptor owner or explicitly document why the final code shape makes one unnecessary. The descriptor does not need to be large, but it must replace duplicated truth rather than sit beside it.

Minimum closure shape:

QueryUnitDescriptor:
  unit: str
  aliases/plural: tuple[str, ...]
  terminal_supported: bool
  exists_supported: bool
  fields: tuple[QueryUnitFieldDescriptor, ...]
  payload_model: type | str
  lowerer_kind: Literal["sql", "runtime_transform", "none"]
  cli_plain_renderer: Callable | None
  docs/completion visibility

It should drive, or mechanically validate, at least:

  • unit names and aliases accepted by the parser;
  • known fields and typed unsupported-field errors;
  • structural exists availability vs terminal-only availability;
  • completion/query-builder metadata;
  • terminal-unit docs/OpenAPI/schema text;
  • CLI plain rendering dispatch;
  • MCP/daemon/Python unit lists;
  • negative behavior for runtime-transform units that must fail closed when a SQL-backed lowerer does not exist.

This is not abstraction for its own sake. It is the mechanism that prevents assertions, observed-events, context-snapshots, future bundles, and future external refs from becoming another set of manually synchronized surfaces.

Typedness hardening still required

A 2026-06-20 pass found the query substrate is only partly typed:

  • QueryUnitName and QueryCompareOp are typed literals.
  • QueryUnitDescriptor centralizes terminal/source metadata.
  • QueryFieldPredicate.field is still a plain str and most field validation happens dynamically through metadata registries.
  • Runtime and SQL lowerers still dispatch on string field names in runtime_matching.py and storage/sqlite/archive_tiers/archive.py.

That is acceptable for the current parser/lowerer bridge, but it should not be the final target. Before #2006 closes, either:

  1. introduce typed field identifiers/descriptors carried by QueryFieldPredicate after parsing, or
  2. make the descriptor registry the canonical typed field object and ensure parser/lowerer/runtime paths pass descriptor-backed values rather than raw unvalidated strings.

Acceptance addition:

  • The post-parse AST should not rely on arbitrary string field names where a closed unit/field descriptor exists. Unknown field text may exist at parser error boundaries, but executable predicates should carry validated descriptor-backed field identity.

Current state (audited 2026-06-27)

Readiness: ~85% already in code · scope L · conflict risk high · depends on: #1883

Assessment & remaining work: The bulk of the query DSL substrate is already shipped: the Lark grammar in expression.py (2634 lines) with typed AST and _bind_predicate_context populating QueryFieldRef on all leaf predicates; explain_query_expression exposed in both CLI (query_explain.py) and MCP (server_tools.py); QueryUnitDescriptor in metadata.py driving all surfaces; sequence predicates (seq()), lineage:id: traversal via recursive CTEs, EXISTS predicates for messages/actions/blocks/assertions/files, pipeline stages (sort/group/count/limit/offset), and runtime-transform terminal units for runs/observed-events/context-snapshots. Remaining work is: (1) integrate with the assertion evidence substrate once #1883 ships — the query_assertions() SQL method and assertions terminal unit descriptor are already wired, only the evidence-linked assertion rows are missing; (2) audit search.md for complete unit/field/operator tables and explicit unsupported-form semantics sections that the docs AC requires.

Primary files: polylogue/archive/query/expression.py, polylogue/archive/query/metadata.py, polylogue/archive/query/predicate.py, polylogue/archive/query/unit_results.py, polylogue/storage/sqlite/archive_tiers/archive.py, docs/search.md

Grounded re-assessment from the 2026-06-27 backlog triage; verify against source before acting.

Activity

  1. added
    type:feat
    theme:command-surface
    area:core
    area:daemon
    theme:analysis
    type:design
    on Jun 16, 2026
  2. 117 remaining items

  3. Sinity commented on Jun 24, 2026

    @Sinity
    OwnerAuthor

    Backlog reshape (Ref #1807): KEEP → Train 2 (Deepen). Backbone for the analysis/blade queries; the postmortem (#2380) and pathology mining (#2383) lower their terminals onto this pipeline. Fold the #2177 QueryUnitDescriptor (§2) and ScopeFilters/QueryRequest (§3) slices into this issue's closure gate (same metadata-scatter fix). Powers depth, not first-contact legibility — hence Train 2, but keep it moving.

  4. Sinity commented on Jun 26, 2026

    @Sinity
    OwnerAuthor

    Concrete next slice, verified against the postmortem (#2380) and sanitized-export (#2381) implementations.

    Both new verbs fold their filter half into the canonical SessionQuerySpec DSL — good. But their terminal half (the distill/export action) is still a CLI-verb → API-method handoff, not a pipeline-AST terminal node. The stage vocabulary has no terminal/transform member:

    polylogue/archive/query/expression.py (QueryUnitPipelineStageKind):

    Literal["session_scope", "sort", "limit", "offset", "group", "count"]

    None represents "run a terminal action over the resolved unit set". So postmortem/export are half-migrated: selection is a pipeline AST; action is dispatched out-of-band, each verb re-implementing its verb→API wiring.

    Proposed slice:

    1. Add Terminal (and likely Transform) members to QueryUnitPipelineStageKind, representing a named terminal action over the resolved query-unit set.
    2. A registry mapping terminal kind → executor (postmortem, sanitized-export, render/count), so one pipeline executor runs the full select → shape → terminal chain.
    3. Route the existing CLI verbs through that executor; the CLI becomes a thin constructor of the pipeline AST + terminal node.

    Acceptance:

    • QueryUnitPipelineStageKind includes terminal/transform kinds, exercised by a test building a full pipeline with a terminal node.
    • Postmortem and sanitized-export reachable as terminal nodes through the single executor; the old per-verb dispatch path removed (grep confirms no second executor).
    • Behavior parity: existing postmortem/export output unchanged (snapshot tests green).

    Ref #2380 Ref #2381 — the two verbs that exposed the terminal-half gap.

  5. removed
    type:design
    on Jun 26, 2026
  6. Sinity commented on Jun 27, 2026

    @Sinity
    OwnerAuthor

    Close-out checklist (post-#2458)

    #2458 made run/observed-event/context-snapshot SQL-backed terminal+exists+sort units and completed the docs-sync slice (docs/search.md now documents them as SQL-backed with the structural-predicate field table; the stale "runtime-transform / reject sort" language is gone).

    Remaining slices to close #2006 (each a complete working layer):

    1. Docs sync — search.md unit/field tables + unsupported-form semantics. Done in feat(insights): materialize run projection into queryable SQL tables #2458.
    2. Terminal/Transform pipeline stage. QueryUnitPipelineStageKind (archive/query/expression.py) has no member for "run a terminal action over the resolved unit set", so postmortem (feat(analyze): add distilled agent-session postmortem bundle #2380) and read/analyze dispatch their action half as a CLI-verb→API handoff outside the pipeline AST. Add Terminal/Transform stage members + a terminal-kind→executor registry so one executor runs select → shape → terminal; route the existing verbs through it (grep-confirm no second executor).
    3. Aggregate gap (intentional, document it). The 3 new units have empty aggregate_group_fields, so group by | count fails typed (correct — no durable count schema yet). Add code comments + docs making the deferral explicit vs forbidden.
    4. Verb refactor. Route read/analyze/delete/bundle through the terminal pipeline dispatch (remove per-verb wiring).
    5. Closure. QueryUnitDescriptor is now effectively the single source of truth; remaining typedness item is QueryFieldPredicate.field still being a plain str (validated during lowering). Decide: carry typed descriptor-backed field identity post-parse, or document why the current bridge is the end state.

    Starting slice 2 (Terminal/Transform stage) now. Design notes in .agent/scratch/313.

    Ref #2380

  7. added a commit that references this issue on Jul 11, 2026
  8. Sinity commented on Jul 26, 2026

    @Sinity
    OwnerAuthor

    2026-07-26 current-reality reconciliation

    Audited against master at b14ec34e and the full issue discussion.

    Disposition: close as completed at the query-substrate level.

    The current grammar and executor support compact/session Boolean queries, terminal units for messages/actions/blocks/files/assertions/runs/observed-events/context-snapshots/delegations, structural exists, action sequences, projections, scoped pipelines, sort/limit/offset, and declared aggregates. The same typed semantics are exposed across CLI, MCP, Python, and HTTP. docs/search.md is generated from a parser-gated discovery corpus with accepted examples, rejected examples, real diagnostics, coverage semantics, continuation semantics, and cost classes.

    A few combinations remain deliberately unsupported, notably semantic vector predicates inside terminal session pipelines until ranked terminal-row semantics are defined. That is an honest boundary, not evidence that the query substrate is missing.

    Future query features should be filed as focused product cases. Keeping this umbrella open would make “full DSL” non-falsifiable and duplicate #1844’s remaining human discovery/completion work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:cliarea:corearea:daemonarea:mcparea:storagetheme:analysistheme:command-surfacetype:feat

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions