Skip to content

feat(query): cwd_prefix filter for session-recall - #543

Merged
Sinity merged 1 commit into
masterfrom
feature/feat/cwd-prefix-and-rename
Apr 27, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/feat/cwd-prefix-and-rename

Conversation

@Sinity

@Sinity Sinity commented Apr 27, 2026 •

Copy link
Copy Markdown
Owner

Summary

First slice of #540. Adds the `cwd_prefix` filter primitive across the full query stack: `ConversationQuerySpec`, `ConversationQueryPlan`, `ConversationRecordQuery`, SQL pushdown, CLI `--cwd-prefix`, MCP `cwd_prefix` param on `list_conversations` and `search`.

Problem

The session-recall workflow needs to filter conversations by the working directory they ran in. Claude Code records carry `cwd` per record; the parser already aggregates these into `provider_meta.working_directories`. But there was no filter primitive to query against it — `--path` filters file paths referenced via tool_use, which is a different question. The deployed sinnix SessionStart hook currently uses `--path` as a workaround.

Solution

  • `ConversationQuerySpec.cwd_prefix`, `ConversationQueryPlan.cwd_prefix`, `ConversationRecordQuery.cwd_prefix` (plumbed via the existing QueryFieldDescriptor system).
  • `ConversationFilterBuilderMixin.cwd_prefix(prefix)` builder method.
  • SQL pushdown in `_build_conversation_filters` using `EXISTS (SELECT 1 FROM json_each(json_extract(provider_meta, '$.working_directories'))) cwd WHERE cwd.value LIKE ? ESCAPE '\\\'`. Works against the existing schema; no migration.
  • CLI flag `--cwd-prefix` registered in shared `click_option_groups`, surfaces on every query verb.
  • MCP `cwd_prefix` param on `list_conversations` + `search`.
  • `MCPConversationQueryRequest.cwd_prefix` threaded into `build_spec`.
  • Witness `tests/data/witnesses/mcp-tool-schemas.json` regenerated for the new MCP shape.

Codex records carry `git.repository_url` rather than `cwd`, so `cwd_prefix` will only match Claude Code conversations until a codex-side enrichment lands. Documented in code comments.

Verification

```bash
nix develop -c devtools verify # full baseline (mypy + render-all + 5642 tests + topology lints) — green
nix develop -c pytest -q tests/unit/core/test_cwd_prefix_filter.py # 11 new tests pass
nix develop -c polylogue --plain --cwd-prefix /realm/project/polylogue --sort date --limit 3 list # returns 3 sessions in this repo
```

Follow-ups (rest of #540)

  • `path` → `referenced_path` rename (clean break, no compat shim).
  • `message_type` filter primitive (recaps surface via `get_messages(id, message_type=summary)`).
  • `since_session(id)` filter.
  • New paginated `get_messages` and `raw_records` MCP tools.
  • MCP resources (`polylogue://conversation/{id}` etc.).
  • Pagination consistency across read tools.
  • CLI mirror of all new params (already started here with `--cwd-prefix`).

Closes the `cwd_prefix` portion of #540.

Summary by CodeRabbit

  • New Features

    • Added --cwd-prefix filter option to the CLI, enabling users to narrow conversation results by filtering based on the recorded working directory prefix
  • Documentation

    • Updated CLI help text and reference documentation to include details about the new working directory prefix filtering option
  • Tests

    • Added comprehensive test coverage for the new working directory prefix filtering functionality

Adds `cwd_prefix` as a first-class filter primitive across the spec /
plan / record-query / SQL pushdown chain, plus CLI `--cwd-prefix` and
MCP `cwd_prefix` parameter on `list_conversations` and `search`.

Pushdown uses `json_extract(conversations.provider_meta, '$.working_directories')`
+ `json_each` so it works against the existing schema with no migration.
Claude Code records carry `cwd` per record; the parser already aggregates
these into `provider_meta.working_directories`.

Codex records do not carry `cwd` directly (only `git.repository_url`),
so cwd_prefix only matches Claude Code conversations until a separate
codex-side enrichment lands.

Why this exists: the SessionStart hook (sinnix) currently uses `--path`
which matches conversations that referenced files under a path. That's
~95% accurate for typical sessions but misses pure-text sessions.
`--cwd-prefix` is the semantically correct filter.

Tests: 11 new tests covering spec → plan → record-query → SQL pushdown →
filter chain → CLI plumbing → MCP request shape → SQL escape behaviour.

Ref #540

Co-Authored-By: Claude <[email protected]>
@coderabbitai

coderabbitai Bot commented Apr 27, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This PR introduces a new --cwd-prefix CLI filter that enables filtering conversations by working directory prefix. The parameter propagates through MCP query contracts, ConversationQuerySpec/Plan construction, query field descriptors, and SQL filtering logic, with comprehensive test coverage.

Changes

Cohort / File(s) Summary
CLI Interface
docs/cli-reference.md, polylogue/cli/click_app.py, polylogue/cli/click_option_groups.py
Introduces new --cwd-prefix TEXT option to top-level polylogue command with parameter propagation through CLI layer.
Query Specification & Planning
polylogue/lib/query/spec.py, polylogue/lib/query/plan.py, polylogue/lib/query/fields.py, polylogue/lib/filter/builder.py
Adds cwd_prefix field to ConversationQuerySpec and ConversationQueryPlan dataclasses, introduces query field descriptor for field mapping, and provides builder method for fluent construction.
Protocol & Storage Interfaces
polylogue/protocols.py, polylogue/storage/query_models.py, polylogue/storage/backends/queries/conversations_reads.py
Extends ConversationReader protocol and storage query TypedDicts/dataclasses with cwd_prefix parameter; threads parameter through read operations (list, list_summaries, count).
SQL Filter Building
polylogue/storage/backends/queries/filter_builder.py
Implements cwd_prefix SQL filtering using JSON extraction of working_directories from provider metadata with LIKE pattern matching and backslash escape handling.
Repository Query Layer
polylogue/storage/repository/archive/queries.py
Adds cwd_prefix parameter to repository mixin query methods and threads through to ConversationRecordQuery construction.
MCP Integration
polylogue/mcp/query_contracts.py, polylogue/mcp/server_tools.py
Extends MCPConversationQueryRequest dataclass and search/list_conversations MCP tool signatures with cwd_prefix parameter.
Tests & Documentation
tests/baselines/showcase/help-main.txt, tests/unit/cli/__snapshots__/test_terminal_snapshots.ambr, tests/unit/core/test_cwd_prefix_filter.py
Updates help text snapshots and adds comprehensive test module validating cwd_prefix propagation, SQL filter generation, wildcard escaping, and integration with other filters.
Tool Schemas
tests/data/witnesses/mcp-tool-schemas.json
Updates MCP tool parameter schemas with reordering and parameter set changes for export_query_results, list_conversations, search, and related tools; adds cwd_prefix and additional filter parameters.

Sequence Diagram

sequenceDiagram
    actor User
    participant CLI
    participant QuerySpec
    participant QueryPlan
    participant StorageLayer
    participant SQLFilter
    participant Database
    
    User->>CLI: polylogue --cwd-prefix "/home/user" search
    CLI->>QuerySpec: from_params(cwd_prefix="/home/user")
    QuerySpec->>QueryPlan: to_plan() with cwd_prefix field
    QueryPlan->>StorageLayer: list_conversations(cwd_prefix="/home/user")
    StorageLayer->>SQLFilter: _build_conversation_filters(cwd_prefix="/home/user")
    SQLFilter->>SQLFilter: Extract working_directories from provider_meta<br/>Build LIKE pattern with escape handling
    SQLFilter->>Database: Execute WHERE EXISTS (SELECT...)<br/>WHERE working_dir LIKE '%/home/user%'
    Database-->>SQLFilter: Filtered conversation records
    SQLFilter-->>StorageLayer: Result set
    StorageLayer-->>CLI: Matched conversations
    CLI-->>User: Display results
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related issues

Suggested labels

type:test, area:cli, area:storage, area:qa

Poem

🐰 A prefix springs forth with CLI cheer,
Through specs and plans, the filter draws near,
SQL whispers through JSON arrays bright,
Working directories match just right,
Conversations now sorted by path's delight! 🌿

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 13.89% 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): cwd_prefix filter for session-recall' clearly and concisely summarizes the main change: adding a cwd_prefix filter capability to the query system for session recall workflows.
Description check ✅ Passed The description is comprehensive and well-structured, covering all required sections: Summary, Problem, Solution, Verification, and Changelog considerations. It provides clear context, implementation details, and verification steps.
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 docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/feat/cwd-prefix-and-rename

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.

@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: bbe51f0596

ℹ️ 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/lib/query/fields.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: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@tests/unit/core/test_cwd_prefix_filter.py`:
- Around line 34-39: The test test_cwd_prefix_escapes_sql_wildcards should also
assert that the backslash escape character itself is escaped in the LIKE
pattern; modify the assertion for params from checking only r"100\%cool\_dir%"
to also check that any returned param string contains an escaped backslash (e.g.
that the pattern includes "\\\\" as the escaped backslash) for the result of
calling _build_conversation_filters(cwd_prefix="/path/100%cool_dir\\"); update
or add an assertion referencing the same params returned by
_build_conversation_filters to verify the escape character is present and
doubled in the SQL LIKE pattern.
🪄 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: 4855fb61-7dd8-478b-8f22-1e09cfd279cb

📥 Commits

Reviewing files that changed from the base of the PR and between e2d602c and bbe51f0.

📒 Files selected for processing (18)
  • docs/cli-reference.md
  • polylogue/cli/click_app.py
  • polylogue/cli/click_option_groups.py
  • polylogue/lib/filter/builder.py
  • polylogue/lib/query/fields.py
  • polylogue/lib/query/plan.py
  • polylogue/lib/query/spec.py
  • polylogue/mcp/query_contracts.py
  • polylogue/mcp/server_tools.py
  • polylogue/protocols.py
  • polylogue/storage/backends/queries/conversations_reads.py
  • polylogue/storage/backends/queries/filter_builder.py
  • polylogue/storage/query_models.py
  • polylogue/storage/repository/archive/queries.py
  • tests/baselines/showcase/help-main.txt
  • tests/data/witnesses/mcp-tool-schemas.json
  • tests/unit/cli/__snapshots__/test_terminal_snapshots.ambr
  • tests/unit/core/test_cwd_prefix_filter.py

Comment on lines +34 to +39
def test_cwd_prefix_escapes_sql_wildcards() -> None:
where, params = _build_conversation_filters(cwd_prefix="/path/100%cool_dir")
assert "ESCAPE" in where
# The escaped prefix has the wildcards escaped
assert any(r"100\%cool\_dir%" in str(p) for p in params)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

Add a backslash-escape assertion for LIKE patterns.

Current wildcard coverage validates % and _, but not \ (the declared escape character). Adding a \ case would better protect the escaping contract.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/unit/core/test_cwd_prefix_filter.py` around lines 34 - 39, The test
test_cwd_prefix_escapes_sql_wildcards should also assert that the backslash
escape character itself is escaped in the LIKE pattern; modify the assertion for
params from checking only r"100\%cool\_dir%" to also check that any returned
param string contains an escaped backslash (e.g. that the pattern includes
"\\\\" as the escaped backslash) for the result of calling
_build_conversation_filters(cwd_prefix="/path/100%cool_dir\\"); update or add an
assertion referencing the same params returned by _build_conversation_filters to
verify the escape character is present and doubled in the SQL LIKE pattern.

@Sinity
Sinity merged commit 8a635ae into master Apr 27, 2026
14 checks passed
@Sinity
Sinity deleted the feature/feat/cwd-prefix-and-rename branch April 27, 2026 20:27
@Sinity

Sinity commented Apr 28, 2026

Copy link
Copy Markdown
Owner Author

🤖 Post-hoc audit note: this PR received bot review feedback verified against current HEAD as part of #544. 1 finding(s) confirmed still present → tracked in #550.

@Sinity
Sinity requested a review from Copilot May 1, 2026 00:45
@Sinity
Sinity requested review from Copilot and removed request for Copilot May 1, 2026 01:05
Sinity added a commit that referenced this pull request May 7, 2026
## Summary

First slice of #540. Adds the \`cwd_prefix\` filter primitive across the
full query stack: \`ConversationQuerySpec\`, \`ConversationQueryPlan\`,
\`ConversationRecordQuery\`, SQL pushdown, CLI \`--cwd-prefix\`, MCP
\`cwd_prefix\` param on \`list_conversations\` and \`search\`.

## Problem

The session-recall workflow needs to filter conversations by the working
directory they ran in. Claude Code records carry \`cwd\` per record; the
parser already aggregates these into
\`provider_meta.working_directories\`. But there was no filter primitive
to query against it — \`--path\` filters file paths *referenced* via
tool_use, which is a different question. The deployed sinnix
SessionStart hook currently uses \`--path\` as a workaround.

## Solution

- \`ConversationQuerySpec.cwd_prefix\`,
\`ConversationQueryPlan.cwd_prefix\`,
\`ConversationRecordQuery.cwd_prefix\` (plumbed via the existing
QueryFieldDescriptor system).
- \`ConversationFilterBuilderMixin.cwd_prefix(prefix)\` builder method.
- SQL pushdown in \`_build_conversation_filters\` using \`EXISTS (SELECT
1 FROM json_each(json_extract(provider_meta, '$.working_directories')))
cwd WHERE cwd.value LIKE ? ESCAPE '\\\\\\'\`. Works against the existing
schema; no migration.
- CLI flag \`--cwd-prefix\` registered in shared
\`click_option_groups\`, surfaces on every query verb.
- MCP \`cwd_prefix\` param on \`list_conversations\` + \`search\`.
- \`MCPConversationQueryRequest.cwd_prefix\` threaded into
\`build_spec\`.
- Witness \`tests/data/witnesses/mcp-tool-schemas.json\` regenerated for
the new MCP shape.

Codex records carry \`git.repository_url\` rather than \`cwd\`, so
\`cwd_prefix\` will only match Claude Code conversations until a
codex-side enrichment lands. Documented in code comments.

## Verification

\`\`\`bash
nix develop -c devtools verify # full baseline (mypy + render-all + 5642
tests + topology lints) — green
nix develop -c pytest -q tests/unit/core/test_cwd_prefix_filter.py # 11
new tests pass
nix develop -c polylogue --plain --cwd-prefix /realm/project/polylogue
--sort date --limit 3 list # returns 3 sessions in this repo
\`\`\`

## Follow-ups (rest of #540)

- \`path\` → \`referenced_path\` rename (clean break, no compat shim).
- \`message_type\` filter primitive (recaps surface via
\`get_messages(id, message_type=summary)\`).
- \`since_session(id)\` filter.
- New paginated \`get_messages\` and \`raw_records\` MCP tools.
- MCP resources (\`polylogue://conversation/{id}\` etc.).
- Pagination consistency across read tools.
- CLI mirror of all new params (already started here with
\`--cwd-prefix\`).

Closes the \`cwd_prefix\` portion of #540.

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

## Summary by CodeRabbit

* **New Features**
* Added `--cwd-prefix` filter option to the CLI, enabling users to
narrow conversation results by filtering based on the recorded working
directory prefix

* **Documentation**
* Updated CLI help text and reference documentation to include details
about the new working directory prefix filtering option

* **Tests**
* Added comprehensive test coverage for the new working directory prefix
filtering functionality

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

Co-authored-by: Claude <[email protected]>
@Sinity

Sinity commented Sep 30, 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.

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