Repository navigation
Conversation
…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]>
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Important Review skippedToo many files! This PR contains 275 files, which is 125 over the limit of 150. ⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: ⛔ Files ignored due to path filters (1)
📒 Files selected for processing (275)
You can disable this status message by setting the Use the checkbox below for a quick retry:
✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
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
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
|
@codex review |
💡 Codex Reviewpolylogue/polylogue/pipeline/services/async_acquisition.py Lines 144 to 148 in 4d16fd3
Line 498 in 4d16fd3 The stats path queries Line 463 in 4d16fd3
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
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]>
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 democommand, 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 underdocs/. 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.pyandpolylogue/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:That split only works if the library surface can consume it directly, so I also extended
polylogue/async_facade.pyinstead of leaving it as a thin read-only wrapper.AsyncPolylogueexposessearch(),parse_file(),parse_sources(),rebuild_index(),filter(),config, andarchive_root, and itsstats()method returns the sameArchiveStatsobject model the sync facade uses. Inpolylogue/facade.pyI renamed the sync parsing entrypoints fromingest_*toparse_*so the vocabulary matches the actual staged runtime.The rename carries through the rest of the stack.
polylogue/pipeline/prepare.pyreplacesingest.py,prepare_ingest()becomesprepare_records(), andIngestionServicebecomesParsingService. 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, andpolylogue/pipeline/watch.pymove notifications, shell hooks, and webhooks behind typed handlers and a reusable watch loop.polylogue/cli/commands/run.pynow 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.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 becausearchive_root(),render_root(), anddb_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.pyintroducesSchemaRegistryandSchemaDiff, giving provider schemas stable version metadata and a place to compare or promote regenerated artifacts.polylogue/schemas/schema_inference.pynow annotates inferred schemas withx-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: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.pyand 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.pyand wired the extras throughpyproject.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.pycentralizes conversation export formatting, andpolylogue/rendering/renderers/html.pyexposesrender_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 inpolylogue/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.pybecomes 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.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 --corpuswrites raw provider-format samples for inspection,--seedbuilds a full demo archive with seeded environment variables, and--showcaseexercises 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.Around that, I moved the packaging and docs to match the active codebase.
pyproject.tomlswitches tohatchling, adds project metadata and the optional tree-sitter extras, and the repo gains GitHub Actions for lint, tests, mypy, coverage, and Nix builds.flake.nixaddshatchlingandvhs, 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 intodocs/cli-reference.md,docs/library-api.md,docs/data-model.md,docs/configuration.md, anddocs/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, andtests/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, andtests/unit/pipeline/test_async_services.pyfor async facade and staged pipeline behavior.tests/unit/core/test_schema.pyfor validation/inference annotations and synthetic round-trips across providers.tests/unit/cli/test_demo.pyandtests/integration/test_workflows.pyfor 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, andtests/integration/test_mcp_resources.pyfor the expanded MCP surface.tests/unit/rendering/test_branch_rendering.pyandtests/unit/security/test_events_security.pyfor 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.