Skip to content

refactor: switch to singleton services and branch-aware storage - #62

Closed
Sinity wants to merge 26 commits into
masterfrom
feature/storage/service-singletons-and-session-branching
Closed

Sinity wants to merge 26 commits into
masterfrom
feature/storage/service-singletons-and-session-branching

Conversation

@Sinity

@Sinity Sinity commented Apr 7, 2026 •

Copy link
Copy Markdown
Owner

Summary

I removed the dependency-injector container, replaced it with a tiny services module, and used the same branch to make conversation lineage a first-class storage concern. The storage layer can preserve raw provider payloads, session continuations, sidechains, and message branches; the repository can traverse that tree; and the domain model no longer has to load every message eagerly just to answer summary-level questions. This also changes the ingest flow: raw bytes are stored first via a new acquisition stage, and parsing/replay happens from raw_conversations without requiring the original provider source to still be present. The CLI follows that shift by consolidating staged execution under run and removing the old sync alias. Across all of that, I tightened role normalization and expanded test/fuzz coverage around the new storage and pipeline behavior.

Motivation

Two architectural problems had started to reinforce each other.

The first was process wiring. The container solved the "where do dependencies come from?" question, but by this point it was more ceremony than clarity. Most commands wanted the same small set of objects, and the storage repository was already the effective center of gravity. Carrying dependency-injector everywhere was no longer buying enough structure to justify the extra layer.

The second was that the archive model still flattened away too much history. ChatGPT edit branches, Claude sidechains, and Codex session continuations were all observable in raw data, but the stored representation had only a weak place to keep that lineage. At the same time, large conversations were getting expensive to load eagerly when many callers only needed counts, summaries, or a stream.

The branch history reflects that progression. It starts with test-isolation fixes and explicit branching metadata, then pushes those fields through ingest, then adds raw conversation capture and staged acquisition, and finally removes the container once the storage/repository model had become simpler and more self-sufficient.

Changes by concern

Module-level services instead of the DI container

polylogue/services.py owns the runtime singletons:

from polylogue.services import get_backend, get_repository, reset

repo = get_repository()

The goal here is not "global state everywhere." It is a very small, explicit composition module for the common process-local objects the application always needs. reset() exists so tests can clear the singleton cache and get a fresh process model.

That let me delete polylogue/container.py entirely and trim polylogue/protocols.py back to the pieces that still make sense as protocols: search, vector search, and rendering. Storage had become simpler to understand as a concrete backend plus repository than as a very large abstract protocol.

Branch-aware storage and raw payload preservation

The biggest capability change is in polylogue/storage/backends/sqlite.py. Schema migrations now add:

  • parent_conversation_id
  • branch_type
  • parent_message_id
  • branch_index
  • raw_conversations

Together, those let the archive preserve both conversation-level lineage (continuations, sidechains) and message-level lineage (edited branch siblings). Raw provider bytes are stored alongside the parsed archive data so later parsing/replay can happen from the database itself rather than from the original provider source.

That is an important shift. It means the ingest story becomes:

  1. acquire raw bytes
  2. persist them
  3. parse from stored raw bytes
  4. materialize archive rows

rather than "read provider export again and hope it is still there."

Added iter_messages() and get_conversation_stats() to the backend so callers can work at summary/stream granularity without forcing full conversation loads.

Unified repository and lazy messages

polylogue/storage/repository.py and polylogue/lib/repository.py are consolidated into one ConversationRepository model that can serve both write and read use cases. New traversal helpers like get_parent(), get_children(), get_root(), and get_session_tree() make the branching data queryable instead of just stored.

On the domain side, polylogue/lib/messages.py introduces MessageCollection, and Conversation.messages is typed as that lazy collection rather than a plain eager list. The idea is:

conv = repo.get(conversation_id)
for msg in conv.messages:
    ...

without paying the memory cost of loading the full message list up front unless the caller really needs to. For those cases, the eager path still exists.

This is one of the bigger review points in the branch because it changes the performance model of the domain object deliberately. Most archive consumers iterate; fewer need random indexing or immediate serialization of the whole message list.

Strict role normalization and branch-aware importers

polylogue/lib/roles.py owns the canonical Role enum plus normalize_role(). Empty strings raise ValueError instead of silently collapsing to a default. That change forces importers to be explicit about missing-role fallbacks, which is healthier than letting invalid role data masquerade as a valid user/assistant event.

The provider importers also emit lineage data:

  • ChatGPT extracts parent_message_provider_id and branch_index from mapping children arrays
  • Claude carries forward parentUuid and marks sidechains
  • Codex detects continuation lineage from multiple session_meta records

prepare_ingest() in pipeline/ingest.py resolves those provider IDs into internal archive IDs and persists them through ConversationRecord and MessageRecord.

Acquisition stage and CLI run

I added polylogue/pipeline/services/acquisition.py so the pipeline can explicitly acquire and store raw provider payloads before parsing. pipeline/services/ingestion.py then reads from raw_conversations rather than from the provider source directly.

This also fits the CLI cleanup. The branch includes the staged run command and removes the deprecated sync alias. That is a breaking CLI change, but it aligns the command surface with the actual pipeline stages much better than carrying two names for the same evolving behavior.

QA, fuzzing, and corpus-backed tests

This branch also adds a lot of verification around the new behavior:

  • tests/test_branching.py and tests/test_branching_pipeline.py
  • tests/test_raw_conversations.py
  • tests/test_pipeline_services_acquisition.py
  • tests/test_cli_run.py
  • tests/test_mcp_server.py
  • parser contract fixtures and seeded databases
  • tests/fuzz/* plus mutmut.toml

The fuzzers target the sorts of inputs that become more important when you are preserving raw payloads and doing stricter role/path handling.

Testing

The new storage/pipeline model is exercised by branching, acquisition, raw-conversation, run-command, and MCP suites, plus fuzz coverage for FTS escaping, path handling, JSON importers, and timestamp parsing. Kept corpus-backed fixtures in the mix so the importer changes are not only validated against tiny synthetic samples.

Notes

Three reviewer-sensitive parts of this branch deserve extra attention.

First, confirm that the lazy MessageCollection contract is clear enough for callers that previously assumed a plain list.

Second, confirm that raw_conversations is storing enough metadata to make replay trustworthy without turning the database into a second, ambiguous source of truth.

Third, check the CLI migration from sync to run carefully. The intent is to make staged execution more explicit, but it does remove a long-standing command alias.

Sinity and others added 26 commits February 2, 2026 02:45
Tests were using `from polylogue.storage.backends.sqlite import
default_db_path` at module load time, capturing a reference before
fixtures could monkeypatch XDG paths. This caused tests to write to
the production database instead of isolated temp directories.

Changes:
- test_check.py: Use db_path fixture instead of default_db_path()
- test_golden_outputs.py: Same pattern fix
- test_store.py: Fixed wrong env var (XDG_STATE_HOME → XDG_DATA_HOME)
  and added proper module reload

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

Co-Authored-By: Claude Opus 4.5 <[email protected]>
Implement schema v7 with unified branching support across all providers:

Storage layer:
- Add parent_conversation_id, branch_type to conversations table
- Add parent_message_id, branch_index to messages table
- Migration from v6 to v7 with indexes

Importers:
- Claude Code: extract parentUuid, detect isSidechain → branch_type
- ChatGPT: extract parent, calculate branch_index from children array
- Codex: track multiple session_meta for continuation detection

Domain model:
- Message: parent_id, branch_index, is_branch property
- Conversation: parent_id, branch_type, is_continuation/is_sidechain/is_root
- mainline_messages() to filter branches

Query API:
- Filters: is_continuation(), is_sidechain(), is_root(), parent(), has_branches()
- Repository: get_parent(), get_children(), get_session_tree(), get_root()

Tests: 13 new branching tests, 2022 total passing

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

Co-Authored-By: Claude <[email protected]>
Critical fix: the branching fields (parent_conversation_id, branch_type,
parent_message_id, branch_index) were being extracted by importers but
NOT copied to storage records during prepare_ingest(). This meant all
branching metadata was silently lost.

Changes:
- Resolve parent_conversation_provider_id → internal conversation ID
- Merge provider_meta instead of overwriting with just source name
- Two-pass message processing to resolve parent_message_id references
- Copy branch_type and branch_index to records

Also adds test_branching_pipeline.py with 8 full-pipeline integration tests
that exercise the REAL importer→ingest→database flow (vs the existing
test_branching.py which uses ConversationBuilder direct DB writes).

Fixed pre-existing property test failure where hypothesis generated
name='.' which gets sanitized to "file" (dots-only security measure).

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

Co-Authored-By: Claude <[email protected]>
Addresses testing gaps identified in Phase 6:

- Add claude-code sample with sidechain branching (57KB)
- Add codex envelope format sample (159KB)
- Add test_fixtures_contract.py for parser validation on real data
- Add seeded_db session fixture in conftest.py
- Refactor extraction tests to use fixtures instead of prod DB paths
- Add iter_branches() to Conversation model for branching support

The seeded_db fixture creates a temp database populated with real
fixture data through the full pipeline, enabling integration tests
without production database contamination.

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

Co-Authored-By: Claude <[email protected]>
Replace raw dict access with model_validate() in codex and claude importers:
- codex.py: Use CodexRecord for format detection and property access
- claude.py: Use ClaudeCodeRecord for type-safe parsing
- claude_code.py: Accept int/float timestamps (not just strings)
- extractors.py: Make codex timestamp optional in glom spec

Benefits:
- Validation at parse time catches malformed data earlier
- IDE autocomplete and type checking work correctly
- Normalized properties (role, text_content) replace manual extraction

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

Co-Authored-By: Claude <[email protected]>
Add comprehensive security-focused fuzzing tests (291 test cases):
- fuzz_path_sanitizer.py: Path traversal attack prevention (44 tests)
- fuzz_fts5_escape.py: FTS5 injection prevention (64 tests)
- fuzz_json_importers.py: Malformed JSON crash resistance (80 tests)
- fuzz_timestamp.py: Timestamp parsing DoS prevention (117 tests)

Add mutation testing configuration:
- mutmut.toml: Target security-critical modules
- Target >80% mutation kill rate

Documentation:
- docs/testing/fuzzing.md: Complete usage guide

Findings:
- FTS5 escape has documented edge cases (xfail markers)
- No SQL injection vulnerabilities (parameterized queries)
- All importers handle malformed input without crashing

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

Co-Authored-By: Claude <[email protected]>
- Move Role enum and normalize_role to polylogue/core/roles.py
- Enforce non-empty input: None and whitespace now raise errors
- Update extractors to use new role module
- Fix tests to expect errors on invalid input

Role validation is now strict - missing roles must be handled at
parse time, not silently defaulted. This preserves data integrity.

Co-Authored-By: Claude <[email protected]>
- Simplify importer base with typed ParsedConversation/ParsedMessage
- Remove redundant conversions in claude_code provider
- Consolidate unified schema definitions
- Update tests for new model structure

Note: Some drive importer tests currently fail due to parser changes
that need further investigation (pre-existing from model migration).

Co-Authored-By: Claude <[email protected]>
Add MessageCollection class that streams messages from DB instead of
loading all into memory. This reduces memory from O(n) to O(1) for
large conversations.

Key changes:
- MessageCollection with lazy/eager modes
- Conversation.from_lazy() factory for streaming
- Repository.get() now returns lazy by default
- Repository.get_eager() for explicit full loading
- Pydantic serialization support for API responses

Performance on 33k message conversation:
- Lazy iteration: 0.08 MB (constant)
- Eager loading: 237 MB
- Improvement: 2,931x memory reduction

API unchanged: for/len/indexing all work. Indexing auto-materializes
for backward compatibility but iteration stays lazy.

Co-Authored-By: Claude <[email protected]>
- Add query output options for large conversations
- Improve CLI help and option grouping
- Support lazy conversation loading in query paths

Co-Authored-By: Claude <[email protected]>
- claude.ai: skip messages without sender/role (no silent defaults)
- drive: skip chunks without role/author (no data invention)
- Update tests to include explicit roles in fixtures
- Add mutants/ to .gitignore

Strict parsing preserves data integrity - missing roles indicate
malformed input that should be skipped, not silently "fixed".

All 2105 tests pass.

Co-Authored-By: Claude <[email protected]>
…e 1)

Add infrastructure to capture and store original JSON bytes before parsing:
- Schema v8: Add raw_conversations table with FK to conversations
- RawConversationRecord model for persistence
- RawConversationData for transport through ingestion pipeline
- Backend methods: save_raw_conversation, get_raw_conversation,
  iter_raw_conversations, link_raw_to_parsed, get_raw_conversation_count
- iter_source_conversations_with_raw() captures raw bytes alongside parsing

Note: Raw capture disabled by default (capture_raw=False) due to SQLite
lock contention with concurrent ingestion. Infrastructure ready for
future single-threaded acquire stage.

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

Co-Authored-By: Claude Opus 4.5 <[email protected]>
- Add AcquisitionService for ACQUIRE stage (files → raw_conversations)
- Refactor IngestionService to orchestrate acquire → parse flow
- Add ingest_from_raw() for parsing from raw_conversations table
- Add source_name column to raw_conversations (schema v9)
- Update tests to mock new stage-based architecture

The pipeline now properly separates concerns:
- ACQUIRE: store raw bytes with content-hash deduplication
- PARSE: read from raw_conversations, parse, store to conversations

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

Co-Authored-By: Claude <[email protected]>
Phase 2: CLI Renaming & Stage Architecture
- Rename `sync` command to `run`
- Add new stages: acquire, parse, generate-schemas
- Keep `sync` as deprecated alias with deprecation warning
- Update tests to use new command name

Phase 3: Type Consolidation
- Delete duplicate ThinkingTrace class (use ReasoningTrace from viewports)
- Document ToolCall vs ToolInvocation distinction:
  - ToolCall (viewports.py): Cross-provider harmonized for rendering
  - ToolInvocation (models.py): Claude-specific with semantic properties

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

Co-Authored-By: Claude <[email protected]>
The CLI was renamed from `sync` to `run` in the previous commit.
This removes the backwards-compat `sync_command` alias and updates
all tests to use the new `run` command name.

- Delete sync_command function and its alias registration
- Convert tests/test_cli_commands.py: TestSyncCommand → TestRunCommand
- Update tests/test_cli.py to use `run` instead of `sync`
- Update --stage "ingest" references to "parse"

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

Co-Authored-By: Claude <[email protected]>
Test consolidation (Phase 6):
- Merge CLI utilities: test_cli_formatting.py + test_cli_helpers.py +
  test_cli_container.py → test_cli_utilities.py (75 tests)
- Remove 9 duplicate test classes from test_db_store.py
- Delete superseded files: test_editor.py (→test_cli_editor.py),
  test_drive_config.py (trivial), test_retries.py (→test_drive_resilience.py),
  test_qdrant.py (→test_qdrant_resilience.py + test_search_index.py)

Result: 102 → 96 test files, 2149 → 2125 tests (no lost coverage)

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

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

Rework schema_inference.py to load raw samples from polylogue database
instead of filesystem crawling.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <[email protected]>
- Add raw_db_samples fixture to conftest.py (reads from polylogue.db)
- Update test_fixtures_contract.py for database-driven validation
- Update test_schema_drift.py for schema evolution tracking
- Update test_raw_conversations.py for raw conversation tests
- Update test_workflows_comprehensive.py for end-to-end validation

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

Co-Authored-By: Claude <[email protected]>
- Update source.py with improved acquisition handling
- Minor runner.py adjustments for stage compatibility
- SQLite backend improvements for raw_conversations

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

Co-Authored-By: Claude <[email protected]>
- Add claude/ fixtures directory with real samples
- Update gemini sample-with-tools.jsonl fixture
- Adjust test_claude_semantic.py and test_importers_drive.py

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

Co-Authored-By: Claude <[email protected]>
New test coverage for MCP server implementation (previously untested).

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

Co-Authored-By: Claude <[email protected]>
Consolidate test files to reduce fragmentation while preserving all tests:

CLI tests (13 → 9 files, -4):
- Merged test_cli_completions.py, test_cli_mcp.py, test_cli_reset.py,
  test_cli_serve.py into test_cli_commands.py
- Preserved both subprocess integration tests AND CliRunner unit tests
- Clear section organization with === banners

Importer tests (7 → 5 files, -2):
- Created test_importers_unit.py consolidating ChatGPT, Claude, Codex
  provider-specific unit tests
- Kept test_importers_parametrized.py (cross-provider integration)
- Kept test_importers_properties.py (Hypothesis property-based)

Results:
- Total test files: 96 → 90 (-6)
- Test count unchanged: 2125 tests passing
- No coverage loss

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

Co-Authored-By: Claude <[email protected]>
Merge fragmented test files into cohesive domain modules:
- CLI: test_cli.py + auth/check/editor/search → test_cli_unit.py, test_cli_integration.py
- Core: test_core_json.py + test_core_utilities.py + test_lib.py → test_core.py
- Storage: test_db.py + test_db_store.py + test_store.py → test_storage.py
- Search: test_search.py + health/providers → test_search_core.py
- Rendering: test_renderers.py + test_rendering_core.py → test_rendering.py
- Backend: test_backend_*.py → test_backend_core.py
- Pipeline: consolidate acquisition/ingestion services

Net reduction: ~6,700 lines via deduplication and shared fixtures.

Co-Authored-By: Claude <[email protected]>
Was declared in pyproject.toml but missing from flake.nix dependencies,
causing pythonRuntimeDepsCheck to fail.

Co-Authored-By: Claude Opus 4.5 <[email protected]>
Phase 1 — Protocol and container cleanup:
- Delete StorageBackend protocol (20 methods, 1 impl) and Renderer protocol (0 impls)
- Keep SearchProvider, VectorProvider, OutputRenderer (2+ impls each)
- Remove 5 isinstance(SQLiteBackend) checks from repository.py; type backend directly
- Replace dependency-injector container (~145 LOC) with services.py (~45 LOC)
- Remove dependency-injector, fastapi, uvicorn from dependencies

Phase 2 — Dissolve core/ package:
- Move facade.py, async_facade.py to polylogue/ top-level
- Move hashing, timestamps, dates, json, log, env, roles to polylogue/lib/
- Move code_detection to polylogue/schemas/
- Move content_enrichment to polylogue/pipeline/enrichment.py
- Rewrite all imports across 48 files
- Delete polylogue/core/ entirely

2096 tests pass, 12 skipped.

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

Co-Authored-By: Claude <[email protected]>
Copilot AI review requested due to automatic review settings April 7, 2026 13:20
@Sinity Sinity added type:refactor Code restructuring area:pipeline Pipeline area:storage Storage labels Apr 7, 2026
@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

Caution

Review failed

Failed to post review comments

📝 Walkthrough

Walkthrough

This PR implements a substantial architectural refactoring removing dependency injection containers, introducing lazy message loading via MessageCollection, adding conversation/message branching support (parent-child relationships), splitting ingest into separate acquire and parse pipeline stages, reorganizing imports from core to lib modules, and evolving the storage schema. It also updates the CLI from sync to run commands with new filtering/output options, adds TUI screens for browsing and searching, and consolidates/refactors the test suite.

Changes

Cohort / File(s) Summary
Container Removal & Service Factory
polylogue/container.py, polylogue/services.py, tests/conftest.py
Deleted centralized DI container; replaced with polylogue/services.py providing lazy singleton factories (get_backend, get_repository, get_service_config, reset). Test fixtures updated to use new service module.
Module Reorganization (core → lib)
polylogue/core/__init__.py, polylogue/health.py, polylogue/pipeline/services/indexing.py, polylogue/pipeline/services/rendering.py, polylogue/storage/search_providers/__init__.py, polylogue/lib/roles.py, polylogue/lib/timestamps.py (implicit), polylogue/schemas/extractors.py
Moved logging, hashing, timestamps, and roles from polylogue.core.* to polylogue.lib.*; created new polylogue/lib/roles.py with centralized Role enum and normalize_role() function.
Import Path Updates
polylogue/__init__.py, polylogue/async_facade.py, polylogue/cli/formatting.py, polylogue/cli/commands/run.py, polylogue/pipeline/enrichment.py, polylogue/pipeline/ids.py, polylogue/importers/base.py, polylogue/schemas/common.py
Updated import sources across facades, CLI, pipeline, importers, and schemas to point to reorganized lib modules.
Repository Refactoring (StorageRepository → ConversationRepository)
polylogue/storage/repository.py, polylogue/lib/repository.py, polylogue/pipeline/ingest.py, polylogue/pipeline/services/ingestion.py
Renamed/refactored repository class; added RepositoryMessageSource adapter, lazy conversation fetching via Conversation.from_lazy(), summary listing, tree traversal methods (get_parent, get_children, get_session_tree, get_root). Updated ingestion pipeline to use new repository type.
Lazy Message Loading & MessageCollection
polylogue/lib/messages.py, polylogue/lib/models.py, polylogue/lib/repository.py, polylogue/lib/filters.py
Introduced MessageCollection class for lazy/eager message iteration; updated Conversation.messages from list[Message] to MessageCollection; added Conversation.from_lazy() for efficient streaming; extended ConversationFilter with summary-based fast path via list_summaries().
Branching Support (Parent/Branch Metadata)
polylogue/storage/store.py, polylogue/storage/backends/sqlite.py, polylogue/lib/models.py, polylogue/importers/base.py, polylogue/importers/chatgpt.py, polylogue/importers/claude.py, polylogue/importers/codex.py, polylogue/importers/drive.py
Added conversation/message branching fields (parent_conversation_id, branch_type, parent_message_id, branch_index); updated importers to extract parent/branch metadata; extended storage schema (v6→v9) with parent-link columns and FTS5 table.
Pipeline Refactoring (Acquire/Parse Stages)
polylogue/pipeline/services/acquisition.py, polylogue/pipeline/services/ingestion.py, polylogue/pipeline/runner.py, polylogue/ingestion/source.py
Added new AcquisitionService stage to capture raw bytes; split ingest into acquire+parse; added iter_source_conversations_with_raw() for raw data streaming; updated prepare_ingest() to handle parent-ID resolution and branching metadata.
Raw Conversation Storage
polylogue/storage/store.py, polylogue/storage/backends/sqlite.py, polylogue/ingestion/source.py
Introduced RawConversationRecord model and backend methods (save_raw_conversation, get_raw_conversation, iter_raw_conversations) to persist original conversation byte payloads with metadata.
CLI Refactoring (sync → run)
polylogue/cli/click_app.py, polylogue/cli/commands/run.py, polylogue/cli/formatting.py, polylogue/cli/query.py
Renamed sync command to run; updated stage options (acquire/parse/render/index/generate-schemas); added --stream, --dialogue-only, --message-limit flags; removed interactive mode from should_use_plain(); simplified query logic and added streaming/summary fast paths.
Query Execution Simplification
polylogue/cli/query.py
Removed regex/annotation/aggregation modes; added lightweight summaries fast path via filter_chain.list_summaries(); added streaming conversation output via stream_conversation(); introduced CSV generation helper; reorganized output logic.
Schema & Extraction Consolidation
polylogue/schemas/unified.py, polylogue/schemas/common.py, polylogue/schemas/extractors.py, polylogue/providers/claude_code.py, polylogue/schemas/claude_code_records.py, polylogue/schemas/schema_inference.py
Centralized role/timestamp normalization in unified extraction; removed per-importer extraction functions from common; updated Claude Code timestamp handling; refactored schema inference to read from raw_conversations table.
Protocol Simplification
polylogue/protocols.py
Removed StorageBackend and Renderer protocols; retained only SearchProvider, VectorProvider, OutputRenderer.
Storage Backend Simplification
polylogue/storage/backends/__init__.py
Simplified create_backend() to remove config-based derivation; now only handles explicit db_path parameter, returns SQLiteBackend directly.
New TUI Screens
polylogue/ui/tui/screens/browser.py, polylogue/ui/tui/screens/search.py
Added Browser screen for hierarchical conversation tree browsing; added Search screen for full-text query with results table and markdown viewer.
Fuzzing Test Suite
tests/fuzz/*
Added comprehensive fuzzing harness for path sanitizer, FTS5 escape, JSON importers, and timestamp parsing; includes seed corpus and pytest-compatible fallback execution.
Test Consolidation & Reorganization
tests/test_backend_core.py, tests/test_branching.py, tests/test_branching_pipeline.py, tests/test_cli_integration.py, tests/test_cli_commands.py, tests/test_cli_run.py, tests/conftest.py, tests/helpers.py
Consolidated backend tests; added branching-specific integration tests; merged CLI tests into new integration/commands modules; refactored fixtures to use new repository/service factories.
Deprecated/Removed Test Files
tests/test_async_repository.py, tests/test_backend_comparison.py, tests/test_backend_protocol.py, tests/test_backend_sqlite.py, tests/test_cli.py, tests/test_cli_auth.py, tests/test_cli_check.py, tests/test_cli_completions.py, tests/test_cli_container.py, tests/test_cli_editor.py, tests/test_cli_formatting.py, tests/test_cli_helpers.py, tests/test_cli_mcp.py, tests/test_cli_reset.py, tests/test_cli_search_expanded.py, tests/test_cli_sync.py
Removed legacy test files covering old DI patterns, sync command, helper utilities, editor/auth/format/MCP logic, and individual CLI features; coverage consolidated into new integrated test modules.
Project Configuration
pyproject.toml, .gitignore, flake.nix, mutmut.toml
Removed fastapi, uvicorn, dependency-injector dependencies; added fuzz optional group; added mutation testing configuration; updated Nix build dependencies.
Public API Changes
polylogue/__init__.py, polylogue/lib/__init__.py, polylogue/ingestion/__init__.py, polylogue/facade.py
Updated top-level imports; added MessageCollection export; added RawConversationData and iter_source_conversations_with_raw to ingestion API; refactored ArchiveStats to remove container dependency.

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Possibly related issues

  • The PR directly implements architectural proposals from related issue discussions: removal of centralized dependency injection, module-level service factories, raw conversation byte preservation, conversation/message branching columns, and lazy/streaming message loading via MessageCollection.

Poem

🐰 The containers have vanished, now services dance free,
Raw bytes flow through pipelines, branching histories we see.
Lazy messages whisper, avoiding full load,
A refactored path forward on the modernization road!
twitches nose enthusiastically ✨

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/storage/service-singletons-and-session-branching

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.

Pull request overview

Note

Copilot was unable to run its full agentic suite in this review.

Refactors application wiring away from dependency-injector into a small services singleton module, and upgrades storage/ingest to be branch-aware with raw payload preservation and a staged acquire→parse pipeline (with CLI moving to run).

Changes:

  • Replace DI container with polylogue/services.py singletons and update call sites.
  • Add branch lineage + raw payload storage (raw_conversations) and update ingest to acquire raw bytes first then parse from DB.
  • Introduce lazy MessageCollection and expand/reshape tests, including fuzz/mutation tooling.

Reviewed changes

Copilot reviewed 87 out of 148 changed files in this pull request and generated 13 comments.

Show a summary per file
File Description
tests/test_cli_serve.py Removed serve command tests (CLI surface changed).
tests/test_cli_search_expanded.py Removed expanded query/search CLI tests (reworked CLI).
tests/test_cli_reset.py Removed reset command tests (suite refactor).
tests/test_cli_mcp.py Removed MCP CLI tests (suite refactor).
tests/test_cli_formatting.py Removed formatting tests (API changed).
tests/test_cli_editor.py Removed editor/browser security tests (suite refactor).
tests/test_cli_container.py Removed DI container tests (container deleted).
tests/test_cli_completions.py Removed completions tests (suite refactor).
tests/test_cli_auth.py Removed auth tests (suite refactor).
tests/test_cli.py Removed legacy sync/search CLI integration tests (CLI moved to run).
tests/test_claude_semantic.py Tunes Hypothesis settings to reduce slowness.
tests/test_check.py Switch tests to use db_path fixture instead of default path.
tests/test_backend_sqlite.py Removed SQLite backend tests (likely replaced elsewhere).
tests/test_backend_comparison.py Removed prod-DB comparison tests (replaced by seeded fixtures).
tests/test_async_repository.py Merged async repository tests into test_async_backend.py.
tests/test_async_backend.py Adds merged async repository tests.
tests/strategies/messages.py Adds Hypothesis strategies returning typed Parsed* model instances.
tests/strategies/init.py Re-exports the new typed strategies.
tests/helpers.py Adds branching helpers and a builder method returning domain objects.
tests/fuzz/fuzz_timestamp.py Adds fuzzing for timestamp parsing/formatting (ReDoS/crash resistance).
tests/fuzz/fuzz_path_sanitizer.py Adds fuzzing for attachment path/name sanitization.
tests/fuzz/fuzz_fts5_escape.py Adds fuzzing for FTS5 query escaping behavior.
tests/fuzz/corpus/README.md Documents seed corpus layout and usage.
tests/fuzz/init.py Adds fuzz test package documentation/entry points.
tests/conftest.py Replaces container reset with service reset; adds seeded DB + raw DB fixtures.
pyproject.toml Removes DI/uvicorn/fastapi deps; adds fuzz extra; adjusts coverage/mypy excludes.
polylogue/ui/tui/screens/search.py Adds a TUI search screen using repository services.
polylogue/ui/tui/screens/browser.py Adds a TUI browser screen for provider trees + preview.
polylogue/storage/store.py Adds branching/raw fields to records and upsert logic.
polylogue/storage/search_providers/init.py Moves env import to polylogue.lib.env.
polylogue/storage/backends/init.py Simplifies backend factory to SQLite-only.
polylogue/services.py Introduces module-level backend/repository singletons with reset().
polylogue/schemas/unified.py Consolidates role/timestamp handling and expands provider text extraction helpers.
polylogue/schemas/schema_inference.py Generates schemas from raw_conversations; loosens nested required.
polylogue/schemas/extractors.py Switches to unified timestamp parsing and stricter role handling.
polylogue/schemas/common.py Re-exports canonical Role from polylogue.lib.roles.
polylogue/schemas/claude_code_records.py Uses unified timestamp parsing; updates return type annotations.
polylogue/providers/claude_code.py Expands timestamp types, reuses unified extractors for tool/reasoning blocks.
polylogue/pipeline/services/rendering.py Moves logger import to polylogue.lib.log.
polylogue/pipeline/services/ingestion.py Implements parse-from-raw flow; adds acquire→parse convenience path.
polylogue/pipeline/services/indexing.py Moves logger import to polylogue.lib.log.
polylogue/pipeline/services/acquisition.py Adds acquisition stage storing raw bytes into raw_conversations.
polylogue/pipeline/runner.py Removes DI wiring; adds acquire/parse stages; updates render/index wiring.
polylogue/pipeline/ingest.py Adds branching/raw_id persistence and parent resolution.
polylogue/pipeline/ids.py Moves hashing imports to polylogue.lib.hashing.
polylogue/pipeline/enrichment.py Switches code detection import path.
polylogue/lib/viewports.py Clarifies ToolCall viewport vs semantic model usage.
polylogue/lib/roles.py Adds canonical Role enum + strict normalize_role().
polylogue/lib/messages.py Introduces lazy MessageCollection w/ pydantic serialization.
polylogue/lib/filters.py Adds branch-aware filters and summary-only query path.
polylogue/lib/init.py Exposes MessageCollection.
polylogue/ingestion/init.py Exports raw capture APIs/types.
polylogue/importers/drive.py Enforces role presence for prompt chunks.
polylogue/importers/codex.py Uses typed CodexRecord parsing; adds continuation lineage.
polylogue/importers/claude.py Uses typed ClaudeCodeRecord parsing; adds sidechain detection + parent UUID.
polylogue/importers/chatgpt.py Adds parent message + branch index extraction.
polylogue/importers/base.py Adds branch metadata fields + RawConversationData; re-exports normalize_role.
polylogue/health.py Moves logger import to polylogue.lib.log.
polylogue/facade.py Removes container usage; creates backend/repository directly; vector provider creation change.
polylogue/core/init.py Deleted (core package API reshaped).
polylogue/container.py Deleted dependency-injector container.
polylogue/cli/formatting.py Updates plain-mode logic (drops interactive parameter).
polylogue/cli/commands/run.py Renames sync→run; adds acquire/parse/generate-schemas stages; uses services config.
polylogue/cli/click_app.py Registers run subcommand; adds streaming options to query-first CLI.
polylogue/async_facade.py Switches record conversion helper import to storage repository.
polylogue/init.py Re-exports facade modules; provides lazy ConversationRepository attribute.
mutmut.toml Adds mutation testing configuration for security-critical modules.
flake.nix Adds glom to dev dependencies.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

cursor_state: dict[str, Any] | None = None,
) -> Generator[ParsedConversation, None, None]:
"""Iterate over conversations from a source with error handling.
def _parse_raw_record(self, raw_record: RawConversationRecord) -> list[ParsedConversation]:

Copilot AI Apr 7, 2026

Copy link

Choose a reason for hiding this comment

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

This will fail for JSONL providers because raw_content can contain multiple JSON objects separated by newlines (not valid for json.loads). Fix by detecting JSONL (e.g., by provider or by scanning for newline-delimited objects) and parsing into a list[dict] before calling _parse_json_payload, or by moving JSON/JSONL decoding into a shared helper used by both acquisition and parsing.

Copilot uses AI. Check for mistakes.
Comment on lines +284 to +292
# Deserialize the raw JSON bytes
payload = json.loads(raw_record.raw_content)

yield from iter_drive_conversations(
source=source,
archive_root=self.archive_root,
ui=ui,
download_assets=download_assets,
cursor_state=cursor_state,
drive_config=self.config.drive_config,
client=client,
)
except DriveAuthError as exc:
logger.warning("Skipping Drive source %s: %s", source.name, exc)
if cursor_state is not None:
cursor_state["error_count"] = cursor_state.get("error_count", 0) + 1
cursor_state["latest_error"] = str(exc)
cursor_state["latest_error_source"] = source.name
return
else:
yield from iter_source_conversations(source, cursor_state=cursor_state)
# Use the existing parser dispatcher
return _parse_json_payload(
raw_record.provider_name,
payload,
raw_record.raw_id, # Use raw_id as fallback conversation ID
)

Copilot AI Apr 7, 2026

Copy link

Choose a reason for hiding this comment

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

This will fail for JSONL providers because raw_content can contain multiple JSON objects separated by newlines (not valid for json.loads). Fix by detecting JSONL (e.g., by provider or by scanning for newline-delimited objects) and parsing into a list[dict] before calling _parse_json_payload, or by moving JSON/JSONL decoding into a shared helper used by both acquisition and parsing.

Copilot uses AI. Check for mistakes.
Comment on lines +144 to +153
record = RawConversationRecord(
raw_id=raw_id,
provider_name=raw_data.provider_hint or source_name,
source_name=source_name, # Config source name, distinct from provider
source_path=raw_data.source_path,
source_index=raw_data.source_index,
raw_content=raw_data.raw_bytes,
acquired_at=acquired_at,
file_mtime=raw_data.file_mtime,
)

Copilot AI Apr 7, 2026

Copy link

Choose a reason for hiding this comment

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

provider_name must reliably be the provider identifier used by parsers (e.g., 'chatgpt', 'claude-code'). Falling back to source_name is unsafe when config source names are things like 'inbox'/'drive', which will break parsing and schema inference. Prefer: (1) require raw_data.provider_hint (or infer provider from source/path/content) and raise/record an error if missing, and (2) keep source_name strictly as the config source label.

Copilot uses AI. Check for mistakes.
Comment thread tests/conftest.py
Comment on lines +606 to +625
# Pre-compute the REAL database path at module load time, before any test
# fixtures can modify environment variables. This ensures database-driven
# tests always use the user's actual database, not a temp test database.
_REAL_DB_PATH = Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local/share")) / "polylogue" / "polylogue.db"


@pytest.fixture(scope="session")
def raw_db_samples():
"""Load samples from user's actual raw_conversations table.

This enables honest, database-driven testing by using REAL data
that was acquired via `polylogue run --stage acquire`.

Control sample count via POLYLOGUE_TEST_SAMPLES environment variable:
- POLYLOGUE_TEST_SAMPLES=100 (default) - Fast CI, limited samples
- POLYLOGUE_TEST_SAMPLES=0 - Exhaustive mode, ALL raw conversations

Returns:
List of RawConversationRecord objects from the user's database
"""

Copilot AI Apr 7, 2026

Copy link

Choose a reason for hiding this comment

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

Tests should not read a developer's real local database by default. This creates nondeterministic failures in CI, potential privacy leaks (local data in test logs), and makes the suite dependent on workstation state. Gate this fixture behind an explicit opt-in env var (e.g., POLYLOGUE_USE_REAL_DB=1), default to pytest.skip(...) when not enabled, and prefer the seeded_db fixture for deterministic integration coverage.

Copilot uses AI. Check for mistakes.
Comment thread tests/conftest.py
Comment on lines +634 to +641
# Use pre-computed path that bypasses test env modifications
if not _REAL_DB_PATH.exists():
return [] # No database = no samples (skip in tests)

backend = SQLiteBackend(db_path=_REAL_DB_PATH)

# Load samples from raw_conversations table
samples = list(backend.iter_raw_conversations(limit=limit))

Copilot AI Apr 7, 2026

Copy link

Choose a reason for hiding this comment

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

Tests should not read a developer's real local database by default. This creates nondeterministic failures in CI, potential privacy leaks (local data in test logs), and makes the suite dependent on workstation state. Gate this fixture behind an explicit opt-in env var (e.g., POLYLOGUE_USE_REAL_DB=1), default to pytest.skip(...) when not enabled, and prefer the seeded_db fixture for deterministic integration coverage.

Copilot uses AI. Check for mistakes.
Comment on lines +46 to +59
# Extract parent message reference and calculate branch index
parent_id = node.get("parent")
parent_message_provider_id = str(parent_id) if parent_id else None
branch_index = 0

# Calculate branch_index from parent's children array position
if parent_message_provider_id:
parent_node = mapping.get(parent_id)
if isinstance(parent_node, dict):
children = parent_node.get("children")
if isinstance(children, list):
current_node_id = node.get("id")
if current_node_id in children:
branch_index = children.index(current_node_id)

Copilot AI Apr 7, 2026

Copy link

Choose a reason for hiding this comment

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

This does a linear children.index(...) scan per message, which can become O(n²) on large conversations with many sibling lists. Consider precomputing an index map per parent (child_id → branch_index) once (or caching it) so branch_index lookup is O(1) during message extraction.

Copilot uses AI. Check for mistakes.
Comment thread polylogue/services.py
Comment on lines +13 to +28
_backend: SQLiteBackend | None = None
_repository: ConversationRepository | None = None


def get_backend() -> SQLiteBackend:
global _backend
if _backend is None:
_backend = create_default_backend()
return _backend


def get_repository() -> ConversationRepository:
global _repository
if _repository is None:
_repository = ConversationRepository(backend=get_backend())
return _repository

Copilot AI Apr 7, 2026

Copy link

Choose a reason for hiding this comment

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

The singleton initialization is not thread-safe: two threads can race and create multiple backends/repositories (and potentially multiple SQLite connections) before assignment. If this module is used from concurrent entry points (TUI workers, thread pools, etc.), add a module-level lock around initialization or use a thread-safe caching approach.

Copilot uses AI. Check for mistakes.
Comment on lines +475 to +482
# =============================================================================
# ASYNC STORAGE REPOSITORY TESTS (merged from test_async_repository.py)
# =============================================================================

from polylogue.lib.models import Conversation, Message
from polylogue.storage.async_repository import AsyncStorageRepository
from polylogue.storage.store import AttachmentRecord, MessageRecord
from polylogue.types import ContentHash

Copilot AI Apr 7, 2026

Copy link

Choose a reason for hiding this comment

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

These imports are placed mid-file after earlier test definitions. This can confuse test discovery tooling and will typically fail linting/isort rules. Move imports to the top of the module (or keep the merged tests in a dedicated file) to match standard Python test structure.

Copilot uses AI. Check for mistakes.
Comment on lines +38 to +40
from polylogue.core.timestamps import parse_timestamp
from polylogue.core.roles import Role, normalize_role as _normalize_role_str
from polylogue.schemas.common import CommonMessage, CommonToolCall

Copilot AI Apr 7, 2026

Copy link

Choose a reason for hiding this comment

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

This appears inconsistent with the new canonical role/timestamp modules introduced in this PR (e.g., polylogue.lib.roles and polylogue.lib.timestamps). If polylogue.core.roles is removed or diverges (and polylogue.schemas.common now re-exports Role from polylogue.lib.roles), this import path can cause runtime ImportError or semantic drift. Align this file to import Role/normalize_role/parse_timestamp from the canonical polylogue.lib.* modules.

Copilot uses AI. Check for mistakes.
@@ -0,0 +1,80 @@
from __future__ import annotations

from rich.markdown import Markdown

Copilot AI Apr 7, 2026

Copy link

Choose a reason for hiding this comment

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

Markdown is imported but not used in this module. Removing unused imports reduces noise and avoids misleading readers about how rendering is performed here.

Suggested change
from rich.markdown import Markdown

Copilot uses AI. Check for mistakes.
Sinity added a commit that referenced this pull request Apr 7, 2026
… branching (#62)

Dissolve the dependency-injector container in favor of plain module-level
factories, simplify the StorageBackend protocol from ~400 lines to ~54,
and introduce session branching with raw conversation preservation.

Service layer (polylogue/services.py, polylogue/container.py):
- Delete container.py and its dependency-injector wiring entirely
- New services.py exposes get_backend(), get_repository(),
  get_service_config(), and reset() as module-level singletons
- Pipeline runner constructs services directly instead of resolving
  through the container

Storage backend (polylogue/storage/backends/sqlite.py):
- Schema migrations v6 → v7 → v8 → v9 add branching columns
  (parent_conversation_id, branch_type, parent_message_id, branch_index)
  and a raw_conversations table for original provider bytes
- iter_messages() enables row-at-a-time streaming without loading
  full conversation into memory
- get_conversation_stats() provides lightweight counts

Repository consolidation (polylogue/storage/repository.py, lib/repository.py):
- Merge former StorageRepository (write) and ConversationRepository (read)
  into a single ConversationRepository with lazy and eager loading modes
- list_summaries() returns ConversationSummary objects (no messages loaded)
- Tree traversal methods for branch navigation

Lazy message loading (polylogue/lib/messages.py, lib/models.py):
- New MessageCollection wraps a backend reference and conversation ID;
  iterates messages on demand with O(1) memory
- Conversation.messages typed as MessageCollection; eager mode available
  via get_eager() for callers that need random access
- Pydantic serialization hooks preserve the lazy/eager distinction

Role normalization (polylogue/lib/roles.py):
- Canonical Role enum and normalize_role() with strict validation
  extracted from scattered per-importer logic
- Empty-string input raises ValueError instead of silently defaulting

Provider importers (importers/chatgpt.py, claude.py, codex.py):
- ChatGPT importer extracts parent_message_provider_id and branch_index
  from mapping children arrays
- Claude importer uses typed ClaudeCodeRecord, detects sidechain branches
  via parentUuid
- Codex importer uses typed CodexRecord, detects session continuations
  from multiple session_metas entries

Pipeline (pipeline/services/acquisition.py, pipeline/services/ingestion.py):
- New AcquisitionService handles the ACQUIRE stage, storing raw bytes
  before any parsing
- Ingestion rewritten to read from raw_conversations table, enabling
  database-driven replay without re-downloading

Package structure:
- Dissolve polylogue/core/ entirely; contents relocated to lib/,
  schemas/, and pipeline/ based on domain ownership
- protocols.py reduced to SearchProvider, VectorProvider, OutputRenderer
@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/storage/service-singletons-and-session-branching branch April 9, 2026 23:02
Sinity added a commit that referenced this pull request Apr 22, 2026
… branching (#62)

Dissolve the dependency-injector container in favor of plain module-level
factories, simplify the StorageBackend protocol from ~400 lines to ~54,
and introduce session branching with raw conversation preservation.

Service layer (polylogue/services.py, polylogue/container.py):
- Delete container.py and its dependency-injector wiring entirely
- New services.py exposes get_backend(), get_repository(),
  get_service_config(), and reset() as module-level singletons
- Pipeline runner constructs services directly instead of resolving
  through the container

Storage backend (polylogue/storage/backends/sqlite.py):
- Schema migrations v6 → v7 → v8 → v9 add branching columns
  (parent_conversation_id, branch_type, parent_message_id, branch_index)
  and a raw_conversations table for original provider bytes
- iter_messages() enables row-at-a-time streaming without loading
  full conversation into memory
- get_conversation_stats() provides lightweight counts

Repository consolidation (polylogue/storage/repository.py, lib/repository.py):
- Merge former StorageRepository (write) and ConversationRepository (read)
  into a single ConversationRepository with lazy and eager loading modes
- list_summaries() returns ConversationSummary objects (no messages loaded)
- Tree traversal methods for branch navigation

Lazy message loading (polylogue/lib/messages.py, lib/models.py):
- New MessageCollection wraps a backend reference and conversation ID;
  iterates messages on demand with O(1) memory
- Conversation.messages typed as MessageCollection; eager mode available
  via get_eager() for callers that need random access
- Pydantic serialization hooks preserve the lazy/eager distinction

Role normalization (polylogue/lib/roles.py):
- Canonical Role enum and normalize_role() with strict validation
  extracted from scattered per-importer logic
- Empty-string input raises ValueError instead of silently defaulting

Provider importers (importers/chatgpt.py, claude.py, codex.py):
- ChatGPT importer extracts parent_message_provider_id and branch_index
  from mapping children arrays
- Claude importer uses typed ClaudeCodeRecord, detects sidechain branches
  via parentUuid
- Codex importer uses typed CodexRecord, detects session continuations
  from multiple session_metas entries

Pipeline (pipeline/services/acquisition.py, pipeline/services/ingestion.py):
- New AcquisitionService handles the ACQUIRE stage, storing raw bytes
  before any parsing
- Ingestion rewritten to read from raw_conversations table, enabling
  database-driven replay without re-downloading

Package structure:
- Dissolve polylogue/core/ entirely; contents relocated to lib/,
  schemas/, and pipeline/ based on domain ownership
- protocols.py reduced to SearchProvider, VectorProvider, OutputRenderer
@Sinity

Sinity commented Apr 28, 2026

Copy link
Copy Markdown
Owner Author

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

@Sinity

Sinity commented May 1, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

💡 Codex Review

from polylogue.core.log import get_logger

P1 Badge Import logger from an existing package path

polylogue.lib.repository imports get_logger from polylogue.core.log, but this commit does not include any polylogue/core package, so importing this repository module raises ModuleNotFoundError immediately. Because other runtime modules (e.g., server and analytics code) import polylogue.lib.repository, this breaks repository-backed flows at import time.


from polylogue.container import ApplicationContainer, create_container

P2 Badge Fix compatibility container import target

polylogue.cli.container now imports ApplicationContainer and create_container from polylogue.container, but that module is not present in this commit. Any caller importing this backward-compatibility module will fail with ModuleNotFoundError before reaching the factory functions.


from polylogue.core.timestamps import parse_timestamp
from polylogue.core.roles import Role, normalize_role as _normalize_role_str

P2 Badge Use valid module paths in schema extractors

polylogue.schemas.extractors imports parse_timestamp and Role from polylogue.core.*, but this commit does not ship that namespace. Importing the extractors module fails immediately, which blocks any extractor usage (and related tests) with a ModuleNotFoundError.

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

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

Labels

area:parser Parser area:pipeline Pipeline area:schema Schema area:storage Storage faux-pull-request PR created as part of a history rewrite process type:refactor Code restructuring

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants