Skip to content

feat: add async pipeline, schema registry, and synthetic corpus - #78

Closed
Sinity wants to merge 19 commits into
masterfrom
feature/feat/1000-tests-mcp-schema-cli-query
Closed

Sinity wants to merge 19 commits into
masterfrom
feature/feat/1000-tests-mcp-schema-cli-query

Conversation

@Sinity

@Sinity Sinity commented Apr 7, 2026 •

Copy link
Copy Markdown
Owner

Summary

I am turning the archive runtime, contract layer, and test corpus into one coherent surface: the pipeline has async acquisition/parsing/rendering/indexing services and an async runner, provider schemas are versioned and annotated strongly enough to drive synthetic wire-format generation, and the CLI/MCP/export layers share more of the same formatting and automation plumbing. The biggest user-visible additions are the polylogue demo command, a much broader MCP server, async facade parity, branch-aware HTML rendering, and CI that exercises lint, tests, typechecking, and Nix builds together. Split the README into focused docs pages so the landing page can stay product-facing while the command, API, configuration, data-model, and MCP references live under docs/. The net effect is that parser work, automation work, and test work move against explicit contracts, not a pile of hand-maintained fixtures and sync-only entrypoints.

Motivation

This branch started with schema-registry/MCP/TUI/test work, but the commit arc made the deeper problem obvious pretty quickly. I first cleaned up the test tree, fixed skips, and renamed the ingestion vocabulary to parsing so the code and CLI were at least speaking the same language. Once that was in place, the real blocker surfaced: too much of the repo still assumed a synchronous runner, static path bindings, duplicated formatting code, and real-export fixtures that were expensive to review and still too narrow to cover the provider edge cases we actually care about.

I considered taking the smaller path and just wrapping the old runner in asyncio.to_thread() while continuing to patch the fixture suite. That would have left stage boundaries, run bookkeeping, and watch-mode side effects coupled to the CLI, and it would have kept the parser contract story implicit. Instead I leaned into a structural move: split the pipeline into async services, make schema artifacts richer and versioned, then use those same schema annotations to generate provider-shaped synthetic corpora. That pivot is what let the async migration, the demo/showcase work, and the test reorganization land as one coherent change instead of three separate partial fixes.

Changes

1. Pipeline and facade parity

The largest architectural change is the new async pipeline path in polylogue/pipeline/async_runner.py and polylogue/pipeline/services/async_*.py. The old sync runner bundled source selection, parsing, rendering, indexing, drift tracking, and run recording together. The new layout makes those concerns explicit:

result = asyncio.run(async_run_sources(
    config=config,
    stage="all",
    plan=None,
    ui=None,
    source_names=None,
))

That split only works if the library surface can consume it directly, so I also extended polylogue/async_facade.py instead of leaving it as a thin read-only wrapper. AsyncPolylogue exposes search(), parse_file(), parse_sources(), rebuild_index(), filter(), config, and archive_root, and its stats() method returns the same ArchiveStats object model the sync facade uses. In polylogue/facade.py I renamed the sync parsing entrypoints from ingest_* to parse_* so the vocabulary matches the actual staged runtime.

The rename carries through the rest of the stack. polylogue/pipeline/prepare.py replaces ingest.py, prepare_ingest() becomes prepare_records(), and IngestionService becomes ParsingService. I wanted the code to stop mixing "ingest" as a generic umbrella term with "parse" as the actual stage that converts raw provider bytes into normalized records.

2. Evented watch mode and safer automation boundaries

Once the pipeline became more explicit, the CLI no longer needed to own every watch-mode side effect itself. polylogue/pipeline/events.py, polylogue/pipeline/event_bus.py, and polylogue/pipeline/watch.py move notifications, shell hooks, and webhooks behind typed handlers and a reusable watch loop. polylogue/cli/commands/run.py now composes those handlers without hardcoding side effects inline.

That paid off in two ways. First, the watch loop is reusable outside the CLI. Second, it gave me a clean place to harden the automation boundaries. The webhook handler validates scheme/host resolution to avoid obvious SSRF targets, and the exec handler rejects shell metacharacters before dispatching through shell=False.

handler = CompositeSyncHandler([
    NotificationHandler(),
    ExecHandler(exec_cmd),
    WebhookHandler(webhook_url),
])
runner = WatchRunner(sync_fn=_sync_once, handler=handler, interval=60)

Used this pass to replace import-time path constants with lazy accessors in polylogue/paths.py. That change looks small, but it removes a lot of hidden coupling in tests and seeded workspaces because archive_root(), render_root(), and db_path() resolve environment overrides when called, not when imported.

3. Versioned schemas and synthetic provider corpora

The contract layer is the other major shift. polylogue/schemas/registry.py introduces SchemaRegistry and SchemaDiff, giving provider schemas stable version metadata and a place to compare or promote regenerated artifacts. polylogue/schemas/schema_inference.py now annotates inferred schemas with x-polylogue-* metadata such as enum-like values, frequency, ranges, detected formats, reference targets, and array-length hints. Added sanitization so those annotations keep structural signals without leaking conversation content into committed schema artifacts.

That contract metadata is what unlocks polylogue/schemas/synthetic.py. Instead of hand-writing or committing real exports, the repo can generate provider-valid JSON/JSONL corpora from the schemas themselves, including tree-shaped formats like ChatGPT and Claude Code:

corpus = SyntheticCorpus.for_provider("chatgpt")
raw_items = corpus.generate(count=3, seed=42)

This was a deliberate pivot from the earlier fixture cleanup commits. I could have kept reorganizing the old samples forever, but the schema annotations were already telling me enough about value ranges, formats, and field frequency to generate better test data than the committed fixtures were providing. That is why tests/integration/test_workflows.py and the parser contract tests move to synthetic sources instead of guarded real-data skips.

Folded optional tree-sitter language detection into polylogue/schemas/code_detection.py and wired the extras through pyproject.toml. Regex detection still works as the fallback, but when the grammars are installed the code can disambiguate close language matches with actual parser error ratios.

4. Shared formatting, richer MCP surface, and HTML branch rendering

A lot of smaller diffs are really one consolidation move. polylogue/lib/formatting.py centralizes conversation export formatting, and polylogue/rendering/renderers/html.py exposes render_conversation_html() so the HTML surface and the CLI/MCP export paths are not maintaining parallel serializers. The HTML renderer also gains _attach_branches() and matching template support in polylogue/rendering/templates/conversation.html, which means branch siblings render as grouped alternatives instead of disappearing into a flat mainline transcript.

On the automation side, polylogue/mcp/server.py becomes a much fuller product surface. I kept the basic read tools, but I added metadata/tag mutation, summary/session-tree/stat-by reads, health and index maintenance hooks, export formatting, new resources, and extra prompts. _safe_call() and _error_json() give the server a consistent structured failure path without leaking tracebacks to clients.

server._tool_manager._tools["export_conversation"].fn(
    id="claude:abc123",
    format="markdown",
)

The MCP work is also where the shared formatter mattered most. I did not want CLI output, HTML exports, and MCP exports to keep drifting on field selection and content rendering.

5. Demo/showcase surface, docs split, packaging, and cleanup

The user-facing capstone is polylogue/cli/commands/demo.py. polylogue demo --corpus writes raw provider-format samples for inspection, --seed builds a full demo archive with seeded environment variables, and --showcase exercises the CLI surface and records a cookbook/report. That command is the practical payoff for the schema-driven corpus work: onboarding, debugging, and demos no longer depend on private archives.

eval $(polylogue demo --seed --env-only)
polylogue dashboard

Around that, I moved the packaging and docs to match the active codebase. pyproject.toml switches to hatchling, adds project metadata and the optional tree-sitter extras, and the repo gains GitHub Actions for lint, tests, mypy, coverage, and Nix builds. flake.nix adds hatchling and vhs, while the obsolete NixOS modules and the stale PR template are removed. The README becomes the product overview and quick start, while detailed reference material moves into docs/cli-reference.md, docs/library-api.md, docs/data-model.md, docs/configuration.md, and docs/mcp-integration.md.

Testing

I treated the test reorganization as part of the feature work, not as cleanup after the fact. The suite is grouped under tests/unit, tests/integration, and tests/infra, with benchmarks/fuzz/manual helpers separated cleanly. The highest-signal coverage for this change is in:

  • tests/unit/test_async_facade.py, tests/unit/pipeline/test_async_helpers.py, and tests/unit/pipeline/test_async_services.py for async facade and staged pipeline behavior.
  • tests/unit/core/test_schema.py for validation/inference annotations and synthetic round-trips across providers.
  • tests/unit/cli/test_demo.py and tests/integration/test_workflows.py for demo seeding/corpus generation and provider end-to-end workflows on synthetic data.
  • tests/integration/test_mcp_mutations.py, tests/integration/test_mcp_exports.py, and tests/integration/test_mcp_resources.py for the expanded MCP surface.
  • tests/unit/rendering/test_branch_rendering.py and tests/unit/security/test_events_security.py for branch-aware HTML and automation hardening.

The CI workflow enforces lint, formatting, strict mypy, and a pytest matrix with --cov-fail-under=90, plus a separate Nix workflow.

Notes

A few things are intentionally conservative in this pass. Tree-sitter support is optional and the regex detector still remains the baseline path. Drive/OAuth behavior is still mocked in test coverage; I did not try to force live credentials into CI. The HTML branch view is sibling-grouped rather than a full interactive tree explorer, because I wanted a readable export that reuses the existing transcript layout. And the old ingest_* / path-constant API names are not preserved as compatibility shims, because keeping both vocabularies alive would have undercut the point of the surface cleanup.

Sinity and others added 19 commits February 12, 2026 23:07
…t optimization

Workstream 1 — Test Runtime (1256s → 309s, 4.1x speedup):
- Lazy path resolution via @functools.cache (eliminates module reloads)
- Convert subprocess CLI tests to CliRunner (40 spawns eliminated)
- Add pytest marks (@slow, @integration) for test partitioning
- Fix 929s mock target bug in test_embed_run_commands.py
- Hypothesis deadline tuning, conditional fixture optimization
- Disable xdist by default (SQLite contention makes it slower)

Workstream 2 — TUI Reliability & Completeness:
- Inject repository into all TUI widgets (DI with fallback)
- Separate data fetching (thread) from DOM mutation (call_from_thread)
- 14 deterministic TUI tests with polling-based _wait_workers()
- FTS index rebuild in search tests

Workstream 3 — Full MCP Server:
- 7 new write tools (tags, metadata, delete_conversation)
- Enhanced read tools (filters, summary, session tree, health)
- Pipeline trigger tools (rebuild_index, render_conversations)
- Export tool with 8 format support
- Error handling hardening, new resources and prompts

Workstream 4 — Schema Registry:
- SchemaRegistry class with versioned storage
- Schema versioning metadata (x-polylogue-* fields)
- Schema health check in `polylogue check`
- Auto-regeneration trigger on drift threshold
- Delete dead mappings.yaml

Cleanup:
- Remove .hypothesis/ from tracking (314 files, was in .gitignore)
- Update .gitignore (result, test.zip, test-manual-verification)
- Fix SQLite isolation in pipeline runner tests
- Fix Hypothesis deadline in security injection tests

4080 tests passing, 0 failures.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
- Delete duplicate fixtures (attachments.json == simple.json, large.json == branching.json)
- Delete orphaned test data (samples/, golden/, manual/, scripts/)
- Delete stale benchmark results and empty fuzz corpus stubs
- Remove dead conftest fixtures (uppercase_json_inbox, raw_backend)
- Remove duplicate variants from CHATGPT_VARIANTS parametrized test
- Add missing __init__.py to polylogue/cli/commands/ package
- Add docstring to empty polylogue/ui/tui/__init__.py
- Rename tests/test-datasets/ → tests/test_datasets/ (snake_case)
- Consolidate and clean .gitignore test data sections
- Delete empty polylogue/schemas/internal/ directory

4029 tests pass, 0 failures.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
…and schema bugs

Test suite reorganization:
- Move 61 flat test files into 7 subdirectories (cli/, storage/, sources/,
  pipeline/, core/, ui/, integration/) mirroring source module structure
- Split 4 monolith files (test_storage.py, test_search_index.py,
  test_core.py, test_cli_commands.py) into 26 focused files
- Merge 3 pairs of related files (branching, security, schema)
- 57 files tracked as git renames, 4 monoliths deleted, 24 new split pieces

Skip fixes (11 → 0 skipped tests):
- conftest.py: stratified random sampling for raw_db_samples (was
  recency-biased, returning only claude-code data)
- conftest.py: seeded_db fixture now populates raw_conversations table
  (was only running parse stage, not acquire stage)
- test_workflows.py: fix claude fixture filename (basic.jsonl → simple.json),
  scan all messages for search test instead of only first
- test_extraction_db.py: add parse_raw_content() for JSONL handling

Pre-existing bugs fixed:
- schema_inference.py: _remove_nested_required() now recurses into
  additionalProperties (was skipping ChatGPT's UUID-keyed mapping subtree,
  leaving stale required arrays that failed all chatgpt validation)
- test_contracts.py: branching test checks parseable content not just
  child count; looks_like mismatches warn instead of fail
- Regenerated all provider schemas from real data

Result: 4,083 passed, 0 failed, 0 skipped (was: 4,072 passed, 11 skipped)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
…bilize flaky TUI test

- pyproject.toml: filter ResourceWarning (sqlite thread-local connections)
  and DeprecationWarning (dateparser strptime, external dep)
- conftest.py: separate acquire (raw_conversations) and parse (prepare_ingest)
  stages to avoid "cannot start transaction within transaction" errors;
  pass raw_id through to link conversations ↔ raw_conversations
- test_tui.py: increase _wait_workers poll from 5s/6 ticks to 10s/10 ticks
  to handle system load jitter in full-suite runs (4000+ tests)

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Split test_crud.py (2211→3), test_drive.py (1910→3), test_mcp.py (1866→4),
test_importers.py (1614→3) into 13 focused files, all under 800 lines.
Extracted shared MCP fixtures into integration/conftest.py.

Renamed 33 duplicate test class names to be globally unique across the
suite (e.g., TestEdgeCases→TestBackendEdgeCases, TestRunCommand→
TestCliRunCommand). No test file exceeds 1,500 lines; zero duplicate
class names remain.

4,079 tests pass, 0 new failures.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Terminology consistency:
- IngestionService → ParsingService, IngestResult → ParseResult/SaveResult
- IngestBundle → RecordBundle, ingest_bundle() → save_bundle()
- prepare_ingest() → prepare_records(), ingest_sources() → parse_sources()
- File renames: ingestion.py → parsing.py, ingest.py → prepare.py
- Test file renames: test_importers_*.py → test_parsers_*.py
- Remove "ingest" stage alias (now just "parse")
- Update all docstrings, comments, and test assertions

ZIP bomb limits:
- MAX_COMPRESSION_RATIO: 100 → 1000 (JSON compresses 100-500x naturally)
- MAX_UNCOMPRESSED_SIZE: 500MB → 10GB (multi-year archives can be large)

CI/CD:
- Add .github/workflows/ci.yml (lint, test matrix, typecheck)
- Add .github/workflows/nix.yml (nix build + flake check)
- Add issue templates (bug report + feature request forms)
- Configure branch protection (require lint, test, nix-build)
- Set repo description, topics, disable wiki

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
…html

Replace the inline f-string HTML generator in cli/query.py with a call
to the new render_conversation_html() function in the rendering module.
Both code paths now share the same Jinja2 template, Pygments highlighting,
and CSS role class sanitization via _role_css_class().

- Add render_conversation_html(conv, theme) free function to html.py
- Add _role_css_class() helper for CSS-safe role class names
- Update conversation.html template to use role_class field
- Remove 60-line _conv_to_html inline HTML generator from query.py
- Update tests for new template structure (html attributes, tag counting)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
…nits

Break down the 288-line function into 6 cohesive components:

- _get_file_mtime(): replaces 2 inline mtime computations
- _record_cursor_failure(): replaces 5 inline cursor_state recordings
- _walk_source_paths() + _build_session_indices(): path resolution
- _ZipEntryValidator: ZIP security (bomb protection, Claude AI filtering)
- _ConversationEmitter + _ParseContext: unified parse/enrich/yield logic
  that collapses 4 near-identical code paths into 2 methods
- _process_zip(): ZIP-specific orchestration

The main function is now a ~45 line orchestrator. Max nesting drops
from 7 levels to 3. Each duplicated pattern (RawConversationData
construction, enrichment, cursor failure recording) now has a single
implementation.

Also fixes: redundant file_mtime/zip_mtime computation for same path.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
…raction

Extract event dispatch (notifications, webhooks, shell exec) from the
CLI layer into pipeline-level abstractions:

- Add pipeline/events.py: SyncEvent, SyncEventHandler protocol,
  CompositeSyncHandler, NotificationHandler, WebhookHandler, ExecHandler
- Add pipeline/watch.py: WatchRunner with configurable interval,
  event dispatch, and idle/error callbacks
- Refactor CLI watch loop to use WatchRunner + CompositeSyncHandler
- Keep backward-compatible _notify/_exec/_webhook wrappers in run.py
- NotificationHandler now correctly skips 0-count notifications
- Add 17 tests for event handlers and watch loop

MCP server, daemons, and batch jobs can now use the same event
system without depending on CLI internals.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Branching conversations (ChatGPT edit branches, Codex continuations)
are now rendered with collapsible <details>/<summary> sections instead
of being flattened into a linear timeline.

- Add _attach_branches() to group branch messages under mainline siblings
- Update _prepare_messages() to fetch parent_message_id and branch_index
- Update render_conversation_html() to include branch metadata
- Add branch CSS: indented border, dashed outline, "Branch N" labels
- Update conversation.html template with branch rendering logic
- Branches are collapsed by default, revealed on click
- Fast path: conversations without branches render identically to before
- Add 10 tests for branch attachment and HTML rendering

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
- Remove unused contextlib import from cli/query.py
- Use collections.abc.Callable instead of typing.Callable in watch.py

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
…r release

Architecture:
- Split monolithic sqlite.py into connection, schema, and sync_adapter modules
- Introduce unified PolylogueError hierarchy in polylogue/errors.py
- Extract event bus into standalone pipeline/event_bus.py
- Extract format_conversation into polylogue/lib/formatting.py
- Add token store for Drive credential management

Features:
- Add tree-sitter code detection backend with regex fallback
- Extend pyproject.toml with tree-sitter optional dependency group
- Add project metadata (license, classifiers, URLs)

Documentation & polish:
- Rewrite README with hero banner, badges, feature table, and GIF demos
- Add CHANGELOG.md, SECURITY.md, and pre-commit config
- Add full docs suite (CLI reference, configuration, data model, library API, MCP)
- Add demo infrastructure (tapes, generate script, seed script)
- Add asset generation script

Tests:
- Add test coverage for event bus, facade, MCP security, token store
- Update existing tests for refactored module paths

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
- Remove docs/archive/ (28 stale internal dev docs)
- Remove nixos-modules/ and flake nixosModules block (phantom
  infrastructure: generated config.json nothing reads, dead options)
- Remove SECURITY.md (boilerplate with placeholder email)
- Remove examples/nixos/sinnix.nix (personal config) and
  examples/reports/ (generated output)
- Remove dead is_declarative() from cli/helpers.py
- Fix mutmut.toml paths (importers/→sources/, core/→lib/)
- Fix AGENTS.md stale nix/devshell.nix reference
- Clean .gitignore: remove 15 dead entries, reorganize
- Fix sys.path hacks and lint in examples/

Co-Authored-By: Claude <[email protected]>
- Remove .githooks/ and unset core.hooksPath (conventional commits
  already enforced by habit, pre-push had blocking `read -p`)
- Remove .gitconfig (project-local aliases/settings unused)
- Remove .pre-commit-config.yaml (pre-commit hook never installed,
  project used .githooks/ instead)
- Remove .github/ bloat: CONTRIBUTING.md, GIT_WORKFLOW.md, SETUP.md
  (1,000+ lines of overlapping git workflow docs — already in CLAUDE.md),
  issue templates, PR template (solo project)
- Keep: CI workflows, .vscode/settings.json, .gitattributes

Co-Authored-By: Claude <[email protected]>
Replaced all references to hardcoded fixture files with SyntheticCorpus-based
test data generation. This eliminates fixture file dependencies while providing
deterministic, schema-driven test data for all providers.

Changes:
- Remove FIXTURES_DIR import
- Replace chatgpt_sample_source and gemini_sample_source fixtures with
  synthetic_source factory-based implementations
- Parametrize test_full_workflow_per_provider with all 5 supported providers
  (chatgpt, claude-ai, claude-code, codex, gemini) using synthetic data
- Remove all None-checking guards from fixtures since synthetic_source always
  succeeds
- Simplify test_multi_source_concurrent_sync to use both sources directly

Co-Authored-By: Claude <[email protected]>
Replace all 6 test data mechanisms with a unified schema-driven synthetic
data system.

Core changes:
- Add SyntheticCorpus generator (polylogue/schemas/synthetic.py) that uses
  genson-inferred JSON Schemas with x-polylogue-* annotations to generate
  valid provider-format test data for all 5 providers
- Add `polylogue demo` CLI subcommand (--seed, --corpus modes)
- Fix FTS5 query escaping: commas are now treated as special characters
- Fix Hypothesis deadline flake in security property test

Test infrastructure:
- Rewrite seeded_db fixture to use SyntheticCorpus (tests/conftest.py)
- Add synthetic_source factory fixture for pipeline testing
- Rewrite Hypothesis strategies to be schema-driven (184 lines vs 314)
- Add 23 schema annotation quality tests
- Add TestSyntheticRoundTrip for end-to-end parse validation
- Migrate all FIXTURES_DIR references to synthetic_source
- Delete test_real_data.py (all coverage now synthetic)

Deleted:
- tests/data/fixtures/ (5 provider fixture directories)
- tests/data/raw/ (gitignored real exports)
- demos/fixtures/ (old hand-crafted synthetic module)
- tests/fixtures/ (removed)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Introduce fully async pipeline replacing sync runner:
- async_runner, async_prepare, and 4 async service modules
  (acquisition, parsing, rendering, indexing)
- Expand async_repository and async_sqlite backend with complete
  query/save/search operations and async_index module
- Add async formatter to rendering core
- Migrate CLI commands (run, demo, helpers) to asyncio.run()
- Wire async service singletons in services.py

Remove obsolete infrastructure:
- Dead examples/, scripts/, nix/direnv-python
- Stale test helpers (cli_helpers/, mocks/)
- Orphaned test modules (event_bus, events_security, facade, mcp_security)
- Minor lint fixes in schema_inference

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
…tests, docs

Complete post-async-migration cleanup:

Phase 1 — Dead code removal:
- Delete sync runner.py (replaced by async_runner.py)
- Delete SyncFromAsyncBackend (unused adapter)
- Migrate 3 test files from sync to async runner

Phase 2 — Package exports:
- Add __all__ to async service modules
- Export async services from pipeline/services/__init__.py
- Export async_run_sources, async_latest_run, plan_sources from pipeline

Phase 3 — AsyncPolylogue facade parity:
- Add search(), parse_file(), parse_sources(), rebuild_index(), filter()
- Upgrade stats() to return ArchiveStats instead of dict
- Resolve circular imports via lazy imports

Phase 4 — New tests (+47):
- test_async_services.py: acquisition, rendering, indexing services
- test_async_helpers.py: async_prepare, async_index helpers
- test_async_facade.py: full AsyncPolylogue facade coverage

Phase 5 — Documentation:
- Fix README slop (~/.../polylogue), remove roadmap, add demo sections
- Add async API docs to library-api.md
- Add demo section to cli-reference.md
- Create docs/demo.md
- Update docs/CLAUDE.md with async pipeline references
- Add MIT LICENSE file

4236 tests passing (net +44 from 4192 baseline).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
Schema sanitization:
- Add _is_safe_enum_value() filter to schema_inference.py to prevent
  x-polylogue-values from capturing unwanted data (emails, file paths,
  long content strings, auth tokens)
- Regenerate all provider schemas with sanitized inference

Showcase system (polylogue demo --showcase):
- 58 exercises across 7 groups exercising the full CLI surface area
- Static wire-format fixtures for 5 providers (12 files)
- Runner engine with CliRunner, validation, topological ordering
- Report generation: summary table, JSON report, Markdown cookbook
- CLI wiring: --showcase, --live, --fail-fast, --json, --verbose flags

Bug fixes discovered during showcase development:
- Fix --fields not respected on --list -f json fast path (query.py)
- Fix mixed-format updated_at SQL comparison: epoch timestamps stored
  as strings failed string comparison against ISO date parameters
  (sqlite.py _build_conversation_filters)
- Fix plain-mode --list rendering (click.echo instead of Rich Table)
- Fix async transaction concurrency bug in _save_via_backend
  (async_repository.py)

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Copilot AI review requested due to automatic review settings April 7, 2026 13:55
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@coderabbitai

coderabbitai Bot commented Apr 7, 2026

Copy link
Copy Markdown

Important

Review skipped

Too many files!

This PR contains 275 files, which is 125 over the limit of 150.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: ae19bd9a-d410-4bd9-a4ae-0e23c246d7ab

📥 Commits

Reviewing files that changed from the base of the PR and between 1003fe6 and 4d16fd3.

⛔ Files ignored due to path filters (1)
  • uv.lock is excluded by !**/*.lock, !**/*.lock
📒 Files selected for processing (275)
  • .github/pull_request_template.md
  • .github/workflows/ci.yml
  • .github/workflows/nix.yml
  • .gitignore
  • .vscode/direnv-python
  • .vscode/settings.json
  • AGENTS.md
  • README.md
  • docs/architecture.md
  • docs/cli-reference.md
  • docs/configuration.md
  • docs/data-model.md
  • docs/library-api.md
  • docs/mcp-integration.md
  • flake.nix
  • mutmut.toml
  • nixos-modules/polylogue.nix
  • nixos-modules/sync.nix
  • polylogue/__init__.py
  • polylogue/async_facade.py
  • polylogue/cli/click_app.py
  • polylogue/cli/commands/__init__.py
  • polylogue/cli/commands/auth.py
  • polylogue/cli/commands/demo.py
  • polylogue/cli/commands/embed.py
  • polylogue/cli/commands/reset.py
  • polylogue/cli/commands/run.py
  • polylogue/cli/commands/site.py
  • polylogue/cli/formatting.py
  • polylogue/cli/helpers.py
  • polylogue/cli/query.py
  • polylogue/config.py
  • polylogue/errors.py
  • polylogue/export.py
  • polylogue/facade.py
  • polylogue/health.py
  • polylogue/lib/__init__.py
  • polylogue/lib/env.py
  • polylogue/lib/filters.py
  • polylogue/lib/formatting.py
  • polylogue/lib/json.py
  • polylogue/lib/models.py
  • polylogue/lib/security.py
  • polylogue/lib/stats.py
  • polylogue/lib/theme.py
  • polylogue/mcp/server.py
  • polylogue/paths.py
  • polylogue/pipeline/__init__.py
  • polylogue/pipeline/async_prepare.py
  • polylogue/pipeline/async_runner.py
  • polylogue/pipeline/event_bus.py
  • polylogue/pipeline/events.py
  • polylogue/pipeline/prepare.py
  • polylogue/pipeline/runner.py
  • polylogue/pipeline/services/__init__.py
  • polylogue/pipeline/services/async_acquisition.py
  • polylogue/pipeline/services/async_indexing.py
  • polylogue/pipeline/services/async_parsing.py
  • polylogue/pipeline/services/async_rendering.py
  • polylogue/pipeline/services/indexing.py
  • polylogue/pipeline/services/parsing.py
  • polylogue/pipeline/watch.py
  • polylogue/rendering/core.py
  • polylogue/rendering/renderers/html.py
  • polylogue/rendering/templates/conversation.html
  • polylogue/schemas/__init__.py
  • polylogue/schemas/code_detection.py
  • polylogue/schemas/mappings.yaml
  • polylogue/schemas/registry.py
  • polylogue/schemas/schema_inference.py
  • polylogue/schemas/synthetic.py
  • polylogue/schemas/unified.py
  • polylogue/services.py
  • polylogue/showcase/__init__.py
  • polylogue/showcase/exercises.py
  • polylogue/showcase/fixtures/chatgpt/showcase-01.json
  • polylogue/showcase/fixtures/chatgpt/showcase-02.json
  • polylogue/showcase/fixtures/chatgpt/showcase-03.json
  • polylogue/showcase/fixtures/claude-ai/showcase-01.json
  • polylogue/showcase/fixtures/claude-ai/showcase-02.json
  • polylogue/showcase/fixtures/claude-ai/showcase-03.json
  • polylogue/showcase/fixtures/claude-code/showcase-01.jsonl
  • polylogue/showcase/fixtures/claude-code/showcase-02.jsonl
  • polylogue/showcase/fixtures/codex/showcase-01.jsonl
  • polylogue/showcase/fixtures/codex/showcase-02.jsonl
  • polylogue/showcase/fixtures/gemini/showcase-01.json
  • polylogue/showcase/fixtures/gemini/showcase-02.json
  • polylogue/showcase/report.py
  • polylogue/showcase/runner.py
  • polylogue/site/builder.py
  • polylogue/sources/__init__.py
  • polylogue/sources/drive.py
  • polylogue/sources/drive_client.py
  • polylogue/sources/parsers/base.py
  • polylogue/sources/parsers/claude.py
  • polylogue/sources/parsers/codex.py
  • polylogue/sources/parsers/drive.py
  • polylogue/sources/source.py
  • polylogue/sources/token_store.py
  • polylogue/storage/__init__.py
  • polylogue/storage/async_index.py
  • polylogue/storage/async_repository.py
  • polylogue/storage/backends/__init__.py
  • polylogue/storage/backends/async_sqlite.py
  • polylogue/storage/backends/connection.py
  • polylogue/storage/backends/schema.py
  • polylogue/storage/backends/sqlite.py
  • polylogue/storage/repository.py
  • polylogue/storage/search.py
  • polylogue/storage/search_cache.py
  • polylogue/storage/search_providers/__init__.py
  • polylogue/storage/search_providers/hybrid.py
  • polylogue/storage/search_providers/sqlite_vec.py
  • polylogue/templates/index.html
  • polylogue/ui/facade.py
  • polylogue/ui/tui/__init__.py
  • polylogue/ui/tui/app.py
  • polylogue/ui/tui/screens/browser.py
  • polylogue/ui/tui/screens/dashboard.py
  • polylogue/ui/tui/screens/search.py
  • pyproject.toml
  • tests/benchmarks/benchmark_caching.py
  • tests/benchmarks/benchmark_pipeline.py
  • tests/benchmarks/benchmark_search.py
  • tests/benchmarks/results_20260123_042644.json
  • tests/cli_helpers/__init__.py
  • tests/cli_helpers/cli_helpers.py
  • tests/conftest.py
  • tests/data/golden/attachments.md
  • tests/data/golden/chatgpt-simple.md
  • tests/data/golden/claude-thinking.md
  • tests/data/golden/empty-messages.md
  • tests/data/golden/markdown-chars.md
  • tests/data/golden/ordering.md
  • tests/data/golden/timestamp.md
  • tests/data/golden/tool-use-json.md
  • tests/data/golden/unicode.md
  • tests/fuzz/__init__.py
  • tests/fuzz/corpus/README.md
  • tests/fuzz/fuzz_fts5_escape.py
  • tests/fuzz/fuzz_json_parsers.py
  • tests/fuzz/fuzz_timestamp.py
  • tests/golden/README.md
  • tests/infra/__init__.py
  • tests/infra/cli_subprocess.py
  • tests/infra/drive_mocks.py
  • tests/infra/helpers.py
  • tests/infra/strategies/__init__.py
  • tests/infra/strategies/adversarial.py
  • tests/infra/strategies/filters.py
  • tests/infra/strategies/messages.py
  • tests/infra/strategies/providers.py
  • tests/integration/__init__.py
  • tests/integration/conftest.py
  • tests/integration/test_click.py
  • tests/integration/test_contracts.py
  • tests/integration/test_extraction_db.py
  • tests/integration/test_facade.py
  • tests/integration/test_health.py
  • tests/integration/test_mcp.py
  • tests/integration/test_mcp_exports.py
  • tests/integration/test_mcp_mutations.py
  • tests/integration/test_mcp_resources.py
  • tests/integration/test_security.py
  • tests/integration/test_semantic.py
  • tests/integration/test_site.py
  • tests/integration/test_workflows.py
  • tests/manual/setup_test_data.sh
  • tests/manual/verify_attachments.sh
  • tests/manual/verify_database.sh
  • tests/manual/verify_filesystem.sh
  • tests/mocks/__init__.py
  • tests/samples/complex_chatgpt.json
  • tests/scripts/extract_real_samples.py
  • tests/scripts/update_golden.py
  • tests/strategies/providers.py
  • tests/test_branching.py
  • tests/test_cli_commands.py
  • tests/test_drive.py
  • tests/test_importers_unit.py
  • tests/test_mcp_server.py
  • tests/test_providers_real_data.py
  • tests/test_search_index.py
  • tests/test_security_injection.py
  • tests/test_storage.py
  • tests/test_tui.py
  • tests/unit/__init__.py
  • tests/unit/cli/__init__.py
  • tests/unit/cli/conftest.py
  • tests/unit/cli/test_analytics.py
  • tests/unit/cli/test_auth.py
  • tests/unit/cli/test_check.py
  • tests/unit/cli/test_commands.py
  • tests/unit/cli/test_demo.py
  • tests/unit/cli/test_embed.py
  • tests/unit/cli/test_helpers.py
  • tests/unit/cli/test_query.py
  • tests/unit/cli/test_query_exec.py
  • tests/unit/cli/test_query_fmt.py
  • tests/unit/cli/test_reset.py
  • tests/unit/cli/test_run.py
  • tests/unit/cli/test_run_int.py
  • tests/unit/cli/test_search.py
  • tests/unit/cli/test_unit.py
  • tests/unit/core/__init__.py
  • tests/unit/core/conftest.py
  • tests/unit/core/test_config.py
  • tests/unit/core/test_export.py
  • tests/unit/core/test_facade.py
  • tests/unit/core/test_filters.py
  • tests/unit/core/test_filters_adv.py
  • tests/unit/core/test_filters_props.py
  • tests/unit/core/test_hashing.py
  • tests/unit/core/test_json.py
  • tests/unit/core/test_models.py
  • tests/unit/core/test_paths.py
  • tests/unit/core/test_properties.py
  • tests/unit/core/test_schema.py
  • tests/unit/pipeline/__init__.py
  • tests/unit/pipeline/test_async_helpers.py
  • tests/unit/pipeline/test_async_services.py
  • tests/unit/pipeline/test_branching.py
  • tests/unit/pipeline/test_event_bus.py
  • tests/unit/pipeline/test_events.py
  • tests/unit/pipeline/test_indexing.py
  • tests/unit/pipeline/test_pipeline.py
  • tests/unit/pipeline/test_prepare.py
  • tests/unit/pipeline/test_runner.py
  • tests/unit/pipeline/test_services.py
  • tests/unit/pipeline/test_watch.py
  • tests/unit/rendering/test_branch_rendering.py
  • tests/unit/security/__init__.py
  • tests/unit/security/test_events_security.py
  • tests/unit/security/test_mcp_security.py
  • tests/unit/sources/__init__.py
  • tests/unit/sources/test_claude.py
  • tests/unit/sources/test_drive_ops.py
  • tests/unit/sources/test_drive_resilience.py
  • tests/unit/sources/test_drive_utils.py
  • tests/unit/sources/test_edge_cases.py
  • tests/unit/sources/test_extraction.py
  • tests/unit/sources/test_models.py
  • tests/unit/sources/test_parser_edge.py
  • tests/unit/sources/test_parser_misc.py
  • tests/unit/sources/test_parsers.py
  • tests/unit/sources/test_parsers_base.py
  • tests/unit/sources/test_parsers_chatgpt.py
  • tests/unit/sources/test_parsers_drive.py
  • tests/unit/sources/test_parsers_props.py
  • tests/unit/sources/test_providers.py
  • tests/unit/sources/test_raw_capture.py
  • tests/unit/sources/test_source_ops.py
  • tests/unit/sources/test_token_store.py
  • tests/unit/storage/__init__.py
  • tests/unit/storage/conftest.py
  • tests/unit/storage/test_async.py
  • tests/unit/storage/test_backend.py
  • tests/unit/storage/test_cache.py
  • tests/unit/storage/test_crud.py
  • tests/unit/storage/test_fts5.py
  • tests/unit/storage/test_hybrid.py
  • tests/unit/storage/test_raw.py
  • tests/unit/storage/test_render.py
  • tests/unit/storage/test_repository.py
  • tests/unit/storage/test_search_misc.py
  • tests/unit/storage/test_sqlite_ops.py
  • tests/unit/storage/test_store_ops.py
  • tests/unit/storage/test_vec.py
  • tests/unit/test_async_facade.py
  • tests/unit/ui/__init__.py
  • tests/unit/ui/test_editor.py
  • tests/unit/ui/test_golden.py
  • tests/unit/ui/test_rendering.py
  • tests/unit/ui/test_tui.py
  • tests/unit/ui/test_ui.py

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/feat/1000-tests-mcp-schema-cli-query

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

Sinity added a commit that referenced this pull request Apr 7, 2026
Split the archive runtime into async parse/render/index services, version
provider schemas, and route demos, exports, and automation through shared
formatting and event hooks.

Pipeline runtime (`polylogue/pipeline/async_runner.py`, `polylogue/pipeline/services/async_*.py`, `polylogue/facade.py`, `polylogue/async_facade.py`):
- add `async_run_sources()`, `async_latest_run()`, `AsyncAcquisitionService`, `AsyncParsingService`, `AsyncRenderService`, and `AsyncIndexService`, which move full runs, indexing, and run recording off the monolithic sync runner and give library callers async parity for parse/search/index flows
- rename `prepare_ingest()` to `prepare_records()`, `IngestionService` to `ParsingService`, and `ingest_file()` / `ingest_sources()` to `parse_file()` / `parse_sources()`, which makes CLI stage names and library APIs line up with acquire → parse → render → index
- replace path constants in `paths.py` with lazy accessors like `archive_root()`, `render_root()`, and `db_path()`, which makes seeded demo environments and env-monkeypatched tests pick up path changes at call time

Schema and synthetic data (`polylogue/schemas/registry.py`, `polylogue/schemas/schema_inference.py`, `polylogue/schemas/synthetic.py`, `polylogue/schemas/code_detection.py`):
- add `SchemaRegistry`, `SchemaDiff`, version metadata, and drift-triggered regeneration hooks, which turn shipped provider schemas into tracked contracts instead of one-off snapshots
- annotate inferred schemas with `x-polylogue-*` statistics and filter `x-polylogue-values` through sanitization rules, which preserve enum and format hints without leaking user content into committed schema artifacts
- add `SyntheticCorpus`, `WireFormat`, and provider-specific tree/message builders, which replace checked-in real fixtures with parser-valid JSON/JSONL corpora and seed full demo archives from schema data
- add optional tree-sitter disambiguation in `code_detection.py`, which improves language labeling for code blocks while preserving regex fallback when extras are absent

CLI, rendering, and MCP (`polylogue/cli/commands/demo.py`, `polylogue/cli/commands/run.py`, `polylogue/pipeline/events.py`, `polylogue/pipeline/event_bus.py`, `polylogue/pipeline/watch.py`, `polylogue/lib/formatting.py`, `polylogue/rendering/renderers/html.py`, `polylogue/mcp/server.py`):
- add `polylogue demo --corpus/--seed/--showcase` and `WatchRunner` plus structured sync handlers, which let demos, watch mode, and external automation consume the same run outputs instead of CLI-local callbacks
- extract shared conversation serializers to `lib/formatting.py` and `render_conversation_html()`, then render branch siblings via `_attach_branches()` and template `<details>` blocks, which removes duplicated export code and makes alternate assistant branches visible in HTML
- expand `mcp/server.py` with mutation, export, health, stats-by, and index tools plus `_safe_call()`, which gives MCP clients tag/metadata management and formatted exports without exposing server tracebacks

Packaging, docs, and QA (`pyproject.toml`, `.github/workflows/*.yml`, `README.md`, `docs/*.md`, `tests/**`, `flake.nix`):
- switch builds to `hatchling`, add tree-sitter extras, CI/Nix checks, and `vhs`, and delete the NixOS modules / PR template dead ends, which makes packaging, demos, and release checks match the active code paths
- split the README into focused docs pages and reorganize tests under `tests/unit`, `tests/integration`, and `tests/infra`, which makes the 1000+ test surface easier to target and lets provider workflows run entirely on synthetic data

Copilot AI 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.

Copilot encountered an error and was unable to review this pull request. You can try again by re-requesting a review.

@Sinity Sinity closed this Apr 9, 2026
@Sinity Sinity added the faux-pull-request PR created as part of a history rewrite process label Apr 9, 2026
@Sinity
Sinity deleted the feature/feat/1000-tests-mcp-schema-cli-query branch April 9, 2026 23:02
Sinity added a commit that referenced this pull request Apr 22, 2026
Split the archive runtime into async parse/render/index services, version
provider schemas, and route demos, exports, and automation through shared
formatting and event hooks.

Pipeline runtime (`polylogue/pipeline/async_runner.py`, `polylogue/pipeline/services/async_*.py`, `polylogue/facade.py`, `polylogue/async_facade.py`):
- add `async_run_sources()`, `async_latest_run()`, `AsyncAcquisitionService`, `AsyncParsingService`, `AsyncRenderService`, and `AsyncIndexService`, which move full runs, indexing, and run recording off the monolithic sync runner and give library callers async parity for parse/search/index flows
- rename `prepare_ingest()` to `prepare_records()`, `IngestionService` to `ParsingService`, and `ingest_file()` / `ingest_sources()` to `parse_file()` / `parse_sources()`, which makes CLI stage names and library APIs line up with acquire → parse → render → index
- replace path constants in `paths.py` with lazy accessors like `archive_root()`, `render_root()`, and `db_path()`, which makes seeded demo environments and env-monkeypatched tests pick up path changes at call time

Schema and synthetic data (`polylogue/schemas/registry.py`, `polylogue/schemas/schema_inference.py`, `polylogue/schemas/synthetic.py`, `polylogue/schemas/code_detection.py`):
- add `SchemaRegistry`, `SchemaDiff`, version metadata, and drift-triggered regeneration hooks, which turn shipped provider schemas into tracked contracts instead of one-off snapshots
- annotate inferred schemas with `x-polylogue-*` statistics and filter `x-polylogue-values` through sanitization rules, which preserve enum and format hints without leaking user content into committed schema artifacts
- add `SyntheticCorpus`, `WireFormat`, and provider-specific tree/message builders, which replace checked-in real fixtures with parser-valid JSON/JSONL corpora and seed full demo archives from schema data
- add optional tree-sitter disambiguation in `code_detection.py`, which improves language labeling for code blocks while preserving regex fallback when extras are absent

CLI, rendering, and MCP (`polylogue/cli/commands/demo.py`, `polylogue/cli/commands/run.py`, `polylogue/pipeline/events.py`, `polylogue/pipeline/event_bus.py`, `polylogue/pipeline/watch.py`, `polylogue/lib/formatting.py`, `polylogue/rendering/renderers/html.py`, `polylogue/mcp/server.py`):
- add `polylogue demo --corpus/--seed/--showcase` and `WatchRunner` plus structured sync handlers, which let demos, watch mode, and external automation consume the same run outputs instead of CLI-local callbacks
- extract shared conversation serializers to `lib/formatting.py` and `render_conversation_html()`, then render branch siblings via `_attach_branches()` and template `<details>` blocks, which removes duplicated export code and makes alternate assistant branches visible in HTML
- expand `mcp/server.py` with mutation, export, health, stats-by, and index tools plus `_safe_call()`, which gives MCP clients tag/metadata management and formatted exports without exposing server tracebacks

Packaging, docs, and QA (`pyproject.toml`, `.github/workflows/*.yml`, `README.md`, `docs/*.md`, `tests/**`, `flake.nix`):
- switch builds to `hatchling`, add tree-sitter extras, CI/Nix checks, and `vhs`, and delete the NixOS modules / PR template dead ends, which makes packaging, demos, and release checks match the active code paths
- split the README into focused docs pages and reorganize tests under `tests/unit`, `tests/integration`, and `tests/infra`, which makes the 1000+ test surface easier to target and lets provider workflows run entirely on synthetic data
@Sinity

Sinity commented May 1, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

💡 Codex Review

return list(
iter_source_conversations_with_raw(
source,
capture_raw=True,
)

P1 Badge Stream source acquisition instead of buffering full iterator

_iter_source_conversations() wraps iter_source_conversations_with_raw() in list(...), so each source is fully loaded into memory before any record is stored. For large JSONL/ZIP exports this can consume multiple GB and fail the acquire stage with OOM, even though the pipeline is otherwise record-oriented. Iterate incrementally (or batch) so acquisition memory stays bounded by a small window of records.


row = conn.execute("SELECT MAX(ended_at) as last FROM runs").fetchone()

P2 Badge Read existing runs timestamp column for last_sync

The stats path queries MAX(ended_at) from runs, but this commit’s runs schema stores timestamp (no ended_at column). In practice this raises and is swallowed by the except, so last_sync is always reported as None even when runs exist. Query the actual persisted column to keep archive stats accurate.


conversations = self._repository.list(limit=10000)

P2 Badge Remove fixed 10k ceiling when computing archive stats

stats() promises totals, but it only loads the first 10,000 conversations. Any archive larger than that will under-report conversation count, provider/tag breakdown, message count, and word count. This produces silently incorrect stats for larger deployments; stats should aggregate over all rows (or use SQL aggregates) instead of a hard cap.

ℹ️ 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".

Sinity added a commit that referenced this pull request Nov 2, 2026
Every agent session pays for MCP `tools/list` and the server
instructions before it asks anything. The integration build sent a 401.6
KB `tools/list` (333 KB of it per-tool `outputSchema`) and 8.2 KB of
instructions that repeated every tool description. This PR brings the
two together under 4,096 bytes of compact JSON and keeps every MCP
capability reachable.

## What changed

- **Four tools instead of one per command.** `polylogue_read`,
`polylogue_context`, `polylogue_note` and `polylogue_chat` are generated
from the command table (`Command::tool`, `commands::Tool`). The shape is
common `command-surface`'s tool family (#78): a call is `{operation,
arguments, request_id, deadline}`, and `operation` is required when a
tool has several rows. `arguments` is the listed arguments of the tool's
rows merged by name, with bare types. An argument that two rows type
differently becomes an `anyOf` naming the rows. Each row checks its own
arguments at dispatch. A comment marks the generator to be replaced by
`OperationTable::mcp_tools` when Polylogue adopts #78.
- **Unlisted arguments.** Options agents rarely need are marked
`unlisted` on their `Arg`. Examples: read's expansions, format and
delivery; cost's month and model; attachment ranges; watch timing. They
stay out of the schema but are accepted and checked. `explain
capabilities` lists each row's tool, its complete argument schema, its
unlisted arguments and its answer schema, plus the answer envelope's
schema once. `polylogue manual` names every argument.
- **No `outputSchema`** on any tool. Results keep `structuredContent`.
- **Instructions are a card** (`docs/agent-manual.md`, 555 B as a JSON
string). The full guidance moves to `docs/agent-guide.md`. `polylogue
manual` prints the card, then the guide, then the generated operation
reference.
- **Ready calls** (`next` on read and attachment pages) now come in the
tool's call form: `{name: polylogue_read, arguments: {operation,
arguments, request_id, deadline}}`.
- **Hints.** `readOnlyHint` comes from the tool's access, and every row
of a tool shares that access. `destructiveHint` is never set.
`idempotentHint` is set except on `polylogue_chat`, because chat send
and backfill start begin a new browser action on every call.
`openWorldHint` is set on `polylogue_chat`.

## Deviations from the brief, agreed with the coordinator

- `timeline` and `cost` stay `polylogue_read` operations. Their
logical-day, calendar and per-model response pages have no
query-language equivalent.
- `list` is not an operation, since it is `sessions where …` through
`query`. `complete` is not an operation either; the protocol's
`completion/complete` covers it.
- `chat list` and `backfill list` are in `polylogue_read`, not
`polylogue_chat`, because a family's rows share one access.
- The envelope carries only `request_id` and `deadline`. #78 will emit
only the envelope options a table declares. Rows built from flat
arguments take a millisecond deadline only, and `deadline: null` is
refused for them with a typed error.

## Deleted

- One tool per command: `Command::mcp`, `Command::mcp_name` and
`Command::typed_mcp_schema`.
- `protocol::operations::McpArguments`, replaced by `ToolCall`.
- Per-tool `outputSchema` and the generated command reference in the
instructions.
- MCP's own kind-to-schema mapping. `commands::kind_schema` is now
shared with `explain`.

## Laws and tests

All in `crates/polylogue/src/mcp/tests.rs` unless noted. The laws are
written in `docs/agents.md`.

- `mcp-surface-size`: `tools_and_instructions_fit_four_kilobytes`.
- `mcp-covers-command-table`:
`every_tool_operation_is_reachable_from_exactly_one_tool`.
- `mcp-tool-access-is-uniform`:
`tool_annotations_follow_the_command_table`.
- `mcp-instructions-are-the-card`:
`server_instructions_are_the_card_naming_every_tool`.
- `mcp-arguments-are-listed-or-explained`:
`every_argument_is_in_its_tool_schema_or_unlisted` and
`typed_operations_declare_every_field_of_their_arguments`.
- `mcp-operation-dispatch`: `a_tool_call_names_one_of_its_operations`.
- `mcp-detail-on-demand`:
`capabilities_publish_each_operation_with_its_tool_unlisted_arguments_and_answer`,
in `explain/tests.rs`.
- Round trips through each removed tool now go through the family call.
The shared helpers `mcp::tests::call` and `call_as` turn a command name
into its family call.
`every_client_answers_the_same_request_identically` runs `list` as a
`query` call and `complete` through `completion/complete`, and compares
both with the CLI and HTTP.

Changed expectations: `mcp_schemas_follow_the_arguments` compared each
tool's `inputSchema` with the row's typed schema. It now checks the
family schema, as `docs/agents.md` "MCP server" states: "The input
schema lists, under `arguments`, the arguments of the tool's rows merged
by name, each with its bare type".

## Verification

- `compile` job 474 (`-p polylogue --tests`): clean, no warnings.
- `focused` job 482: 87 of 88 tests passed, including the size gate and
reachability. The run hit the 30-minute job timeout after a 29-minute
cold build, while
`read_pages::budgeted_mcp_output_contains_one_bounded_layout_and_no_duplicate_source_records`,
a long whole-byte read, was still running.
- `focused` job 573 on the final head: see the follow-up comment.
- Measured sizes come from a model of the generator over the command
table; the size test asserts them in-process. `tools/list` is about 3.4
KB and the instructions 555 B, which is under the 4,096 B limit.
- Not done: the live `polylogue mcp` measurement after deploy.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01AcQETkbTfFMr1hgNJ8A3em

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:cli CLI area:docs Docs area:mcp MCP area:nix Nix area:parser Parser area:pipeline Pipeline area:qa QA area:schema Schema area:storage Storage faux-pull-request PR created as part of a history rewrite process type:feat New feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants