Repository navigation
Description
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.pyowns the Lark grammar, field registry, structural unit registry, typed parser errors, AST/explain output, and the historicalcompile_expressionpublic entrypoint.compile_expressionis 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.pydefinesSessionQuerySpec, query planning, and the shared query selection contract used by current read surfaces.polylogue/archive/query/predicate.pycarries the typed Boolean/structural/semantic/sequence predicate nodes that are already lowerable where supported.polylogue/storage/repository/archive/queries.pyand 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.pyconsumesEXPRESSION_FIELD_REGISTRYand 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:staleand-"bad phrase"; - count comparisons for
messagesandwords; - explicit Boolean predicates such as
sessions where (repo:polylogue OR origin:chatgpt-export) AND NOT tag:stale; - cross-field Boolean
AND/OR/NOTover supported SQL-backed session fields; - FTS predicates and semantic predicates with typed rank semantics where available;
exists message(...),exists action(...),exists block(...), andexists 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(...), orexists 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:
sessionsmessagesblocksactions/ tool calls / tool resultsrunsobserved-eventsassertionscontext-snapshotsbundleslineagefiles/ 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
- feat(query): sort terminal pipeline rows by time (#2006) #2187 added
sort by time [asc|desc]for SQL-backed terminal query rows and documented typed rejection for runtime-transform terminal units without durable sort lowerers.
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:
- Extend comparison/range operators beyond count and date clauses for the remaining SQL-backed session fields.
- 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. - Add sequence predicates for realistic edit -> test fail -> edit and review/check workflows.
- Add pipeline stages for traversal, aggregation, sort/limit, and terminal read/analyze/bundle actions.
- Add bundle/file/external-ref/phase/thread/span units only where the owning substrate is ready enough to execute real rows.
- Keep completion/MCP/web query-builder metadata sourced from the same AST/field/unit registries.
- 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:
- Current supported session query strings lower through the canonical Lark-backed compiler with behavior equivalent to current releases or stricter typed errors.
- Cross-field Boolean over SQL-backed session fields lowers to SQL predicates.
- FTS and semantic legs lower to existing search/vector paths with explicit rank semantics.
- Message/action/block predicates lower to EXISTS subqueries over messages, blocks, and action/tool rows.
- Sequence predicates lower over ordered action/message/event evidence.
- Lineage/topology traversal lowers through existing topology/logical-session data, using recursive CTEs where needed.
- Assertion predicates lower through the assertion substrate; run/event/context-snapshot terminal rows lower through the recovery/run projection.
- Bundle/file/external-ref/phase/thread/span units lower through concrete owning substrates before they become accepted grammar.
- 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.
--explainor 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_expressionmay 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
- Parent product epic: EPIC: Polylogue as local AI-work evidence cockpit #1807.
- Completion/query builder should consume this grammar metadata: Build completion on shared query grammar #1844.
- MCP/Python/API parity must route through this shared substrate: Keep MCP and Python API on shared query/read contracts #1825.
- Recovery, forensic, and work-packet views provide early report pressure: Transform raw agent sessions into on-demand recovery views #1880, Fold agent workflow events into recovery/work views #1840, Render work packets as on-demand evidence bundles #1838, Define evidence-linked session view profiles #1997.
- Assertion/run/event units depend on Unify user overlays as evidence-linked assertions #1883 and Model runs, context snapshots, and observed events #1882 substrate surfaces.
- Earlier flat-expression work (Implement query expression compiler shared by CLI, web, MCP, and Python API #1812-era) is background only; this issue owns one grammar and one AST/lowering pipeline.
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 visibilityIt should drive, or mechanically validate, at least:
- unit names and aliases accepted by the parser;
- known fields and typed unsupported-field errors;
- structural
existsavailability 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:
QueryUnitNameandQueryCompareOpare typed literals.QueryUnitDescriptorcentralizes terminal/source metadata.QueryFieldPredicate.fieldis still a plainstrand most field validation happens dynamically through metadata registries.- Runtime and SQL lowerers still dispatch on string field names in
runtime_matching.pyandstorage/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:
- introduce typed field identifiers/descriptors carried by
QueryFieldPredicateafter parsing, or - 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
fix: retarget query DSL planning and restore quick gate (#2007)
feat(query): expose query expression explain payload
docs(query): define Lark as the query grammar
feat(query): parse query expressions with Lark (#2006) (#2009)
feat(query): execute Boolean session predicates
feat(query): execute Boolean session predicates (#2006) (#2010)
117 remaining items
test(cli): cover json alias across query actions (#2367)
feat(cli): expose json aliases on action commands (#2368)
Sinity commentedon Jun 24, 2026
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.
Sinity commentedon Jun 26, 2026
Concrete next slice, verified against the postmortem (#2380) and sanitized-export (#2381) implementations.
Both new verbs fold their filter half into the canonical
SessionQuerySpecDSL — 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):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:
Terminal(and likelyTransform) members toQueryUnitPipelineStageKind, representing a named terminal action over the resolved query-unit set.select → shape → terminalchain.Acceptance:
QueryUnitPipelineStageKindincludes terminal/transform kinds, exercised by a test building a full pipeline with a terminal node.Ref #2380 Ref #2381 — the two verbs that exposed the terminal-half gap.
feat(insights): deterministic agent-workflow pathology detectors (#2448)
feat(insights): expose pathology distribution via API + MCP tool (#2383…
feat(insights): emit pathology findings as candidate assertions (#2383)…
Sinity commentedon Jun 27, 2026
Close-out checklist (post-#2458)
#2458 made
run/observed-event/context-snapshotSQL-backed terminal+exists+sort units and completed the docs-sync slice (docs/search.mdnow 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):
Docs sync — search.md unit/field tables + unsupported-form semantics.Done in feat(insights): materialize run projection into queryable SQL tables #2458.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. AddTerminal/Transformstage members + a terminal-kind→executor registry so one executor runsselect → shape → terminal; route the existing verbs through it (grep-confirm no second executor).aggregate_group_fields, sogroup by | countfails typed (correct — no durable count schema yet). Add code comments + docs making the deferral explicit vs forbidden.read/analyze/delete/bundle through the terminal pipeline dispatch (remove per-verb wiring).QueryFieldPredicate.fieldstill being a plainstr(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
feat(insights): materialize run projection into queryable SQL tables (#…
feat(query): add Terminal pipeline stage; route unit terminals via re…
feat(query): add Terminal pipeline stage; route verbs through one exe…
chore(release): 0.2.0 (#2102)
Sinity commentedon Jul 26, 2026
2026-07-26 current-reality reconciliation
Audited against
masteratb14ec34eand 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.mdis 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.