Repository navigation
Conversation
|
Caution Review failedFailed to post review comments 📝 WalkthroughWalkthroughReplaces the monolithic CLI with a modular cli package and new entrypoint, consolidates provider sync/import subcommands, moves conversation outputs to per-slug directories ( Changes
Sequence Diagram(s)sequenceDiagram
participant CLI as CLI (polylogue.cli.app)
participant Cmd as Command Handler
participant Repo as ConversationRepository
participant FS as Filesystem
participant DB as StateStore/SQLite
participant Drive as DriveClient
CLI->>Cmd: parse args & dispatch (e.g., "sync codex")
Cmd->>Repo: build document via pipeline (chunks, attachments, html opts)
Repo->>Drive: (optional) download attachments
Drive-->>Repo: metadata / downloaded files
Repo->>FS: write <slug>/conversation.md, attachments/, conversation.html
Repo->>DB: persist state and run records
DB-->>Cmd: persistence outcome (slug, paths, diff)
Cmd-->>CLI: emit JSON/plain summary
Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes Possibly related issues
Poem
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
⚔️ Resolve merge conflicts
|
…t paths (#16) Decompose the 1835-line polylogue/cli.py into a polylogue/cli/ package with focused submodules, migrate all hardcoded paths to XDG base directories, switch per-conversation output from flat files to directory layout, and add branch exploration plus FTS5 search surfaces. CLI package decomposition (polylogue/cli/): - app.py: parser, main(), interactive_menu, inspect commands, prune - context.py: shared defaults, HTML tri-state resolution, settings init - sync.py: Drive/Codex/Claude Code sync with unified dispatch - imports.py: ChatGPT/Claude/Codex/Claude Code import wrappers - render.py: render command and clipboard copy helper - watch.py: provider-agnostic file watcher with debounce - status.py: status dashboard and stats aggregation - doctor.py: health check with state/database pruning - automation_cli.py: systemd/cron snippet generation - summaries.py: OperationSummary via results.py for import output Command surface redesign: - sync-codex / sync-claude-code / sync → sync codex|claude-code|drive - stats → inspect stats; new inspect branches and inspect search - --html flag changes from boolean to tri-state on|off|auto - new prune command removes legacy flat-file outputs - automation_targets.json updated for new command syntax XDG and path migration (polylogue/util.py, config.py): - CONFIG_HOME, DATA_HOME, CACHE_HOME, STATE_HOME derived from XDG vars - /realm/data/chatlog/ replaced with $XDG_DATA_HOME/polylogue/archive - _attachments/ directories renamed to attachments/ - slug.md layout becomes slug/conversation.md with slug/attachments/ - CODEX_SESSIONS_ROOT, CLAUDE_CODE_PROJECT_ROOT env-overridable New domain modules: - branch_explorer.py: tree rendering, HTML explorer, unified diff - search.py: FTS5 query execution with provider/model/date/attachment filters and skim-driven preview picker - pipeline.py: ChatContext and build_document_from_chunks extracted from commands.py; attachment collection with mtime-aware re-download - repository.py: ConversationRepository facade over document_store - results.py: OperationSummary aggregation replacing inline summaries Infrastructure hardening: - util.py: StateStore with mutate() for atomic state updates; DiffTracker and RunAccumulator replace ad-hoc snapshot management - commands.py: RunSummaryEntry/ProviderSummaryEntry replace nested dicts; _persist_conversation centralises write+diff+state - document_store.py: content hash now covers metadata; stale attachment cleanup; HTML removal when disabled - index.py: IndexBackend protocol with SqliteBackend, QdrantBackend, NullBackend behind POLYLOGUE_INDEX_BACKEND env switch - importers/utils.py: safe_extractall blocks zip path traversal - html.py: template/renderer caching; markupsafe.escape for XSS Nix packaging (flake.nix, nix/devshell.nix): - re2 overlay extracted to module-level binding - cliDeps (gum, skim, delta, git) bundled via makeWrapper - tiktoken and qdrant-client added to baseDeps - checkPhase sets XDG_STATE_HOME/XDG_CACHE_HOME for isolation - devshell gains pytest, pytest-cov, coverage, mypy, types-requests Testing: - conftest.py: tiktoken stub for deterministic token counts - new test files: branch_and_search, cli_flags, cli_wrappers, document_store_cleanup, drive_client, importers_security, pipeline, results - pyproject.toml: pytest/coverage/mypy configuration added
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: fe40a1d0c5
ℹ️ 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".
There was a problem hiding this comment.
Pull request overview
This PR refactors Polylogue’s monolithic CLI into a polylogue/cli/ package organized by command surface, replaces hardcoded paths with XDG base directory resolution, and introduces new inspection/prune capabilities while migrating outputs to a per-conversation directory layout.
Changes:
- Split CLI into modular command handlers (
render,sync,import,watch,status/stats,doctor,automation,inspect,prune) with shared defaults incli/context.py. - Migrate archive/output paths to XDG defaults and change output layout to
<slug>/conversation.md+<slug>/attachments/. - Add new domain helpers (
pipeline.py,repository.py,results.py,search.py,branch_explorer.py) plus expanded tests and Nix packaging updates.
Reviewed changes
Copilot reviewed 71 out of 71 changed files in this pull request and generated 9 comments.
Show a summary per file
| File | Description |
|---|---|
| AGENTS.md | Updates repository guide to point to docs/ workflows. |
| README.md | Updates usage docs for new sync <provider> syntax, inspect/prune commands, and new output layout/XDG paths. |
| docs/providers/chatgpt.md | Updates attachment/output layout documentation. |
| docs/providers/claude-ai.md | Updates attachment/output layout documentation. |
| docs/providers/claude-code.md | Updates command names and attachment directory naming. |
| docs/providers/gemini.md | Updates Drive sync command and attachment layout notes. |
| docs/providers/openai-codex.md | Updates command names and attachment directory naming. |
| flake.nix | Adds CLI tool deps (gum/skim/delta/git), wraps binary PATH, adjusts check env for XDG, adds deps (tiktoken/qdrant-client), factors overlay. |
| nix/devshell.nix | Switches to a pythonEnv and adds new Python deps + CLI tools. |
| polylogue/automation.py | Switches automation execution to python -m polylogue.cli, improves quoting and systemd path escaping. |
| polylogue/automation_targets.json | Updates automation target commands to sync <provider> form. |
| polylogue/branch_explorer.py | Adds branch graph loading/rendering, HTML explorer generation, and unified diffs. |
| polylogue/branching.py | Adjusts branch plan scoring and canonical branch metadata. |
| polylogue/cli/init.py | Adds CLI shim exports for backward-compatible imports and helpers. |
| polylogue/cli/app.py | New main CLI app/parser wiring, inspect commands, prune CLI, interactive flows. |
| polylogue/cli/automation_cli.py | New CLI surface for printing automation snippets and describe output. |
| polylogue/cli/context.py | Centralizes CLI defaults/resolution (HTML mode, collapse threshold, output paths). |
| polylogue/cli/doctor.py | CLI wrapper for doctor output (plain/rich + JSON). |
| polylogue/cli/imports.py | New import subcommand dispatch + picker logic + summaries/clipboard integration. |
| polylogue/cli/render.py | New render CLI wrapper with picker + JSON/plain summaries + clipboard support. |
| polylogue/cli/status.py | New status/stats CLI wrappers, including stats over new directory layout. |
| polylogue/cli/summaries.py | Adds shared import summary rendering via OperationSummary. |
| polylogue/cli/sync.py | New sync <provider> wrapper combining Drive sync + local sync flows with consistent reporting. |
| polylogue/cli/watch.py | New watch <provider> wrapper for provider-agnostic watcher dispatch. |
| polylogue/cli_common.py | Updates filtering semantics and adds generic skim single-selection helper; updates prune path logic for new layout. |
| polylogue/commands.py | Integrates new pipeline/repository/search/branches commands; updates provider/run summaries and new output layout. |
| polylogue/config.py | Moves archive root to XDG data (POLYLOGUE_ARCHIVE_ROOT override) and aligns config dir with XDG. |
| polylogue/conversation.py | Routes persistence via repository facade; writes branch artifacts in new per-conversation directory layout. |
| polylogue/doctor.py | Adds pruning of stale state and DB entries; adds managed-dir safety checks. |
| polylogue/document_store.py | Updates persistence to per-conversation directory layout; adds metadata-inclusive content hashing + attachment/HTML cleanup behavior. |
| polylogue/drive.py | Improves retry env overrides and escapes Drive folder name in query. |
| polylogue/drive_client.py | Adds env-based credential injection/copy and improves credential prompting flow. |
| polylogue/html.py | Caches markdown renderer/Jinja template and escapes metadata in fallback HTML path. |
| polylogue/importers/base.py | Extends ImportResult with slug. |
| polylogue/importers/chatgpt.py | Uses safe zip extraction and new output layout; sanitizes attachment filenames. |
| polylogue/importers/claude_ai.py | Uses safe zip extraction and new output layout; sanitizes attachment filenames. |
| polylogue/importers/claude_code.py | Uses XDG base dir default, new output layout, and improved session ordering/selection. |
| polylogue/importers/codex.py | Uses XDG base dir default, new output layout, and improved session selection behavior. |
| polylogue/importers/utils.py | Makes tiktoken a required dependency; adds safe zip extraction helpers. |
| polylogue/index.py | Introduces IndexBackend protocol with sqlite/null/qdrant implementations and backend caching. |
| polylogue/index_qdrant.py | Tightens qdrant error handling (404 recreate) and removes silent import swallowing. |
| polylogue/local_sync.py | Updates sync logic for new output layout; adds DiffTracker and more robust up-to-date detection + prune. |
| polylogue/options.py | Adds slug to render/sync results; adds options/results dataclasses for branch explore + search. |
| polylogue/pipeline.py | Extracts chunk→document building and attachment collection (including mtime-based download avoidance). |
| polylogue/render.py | Narrows optional dependency exception handling for frontmatter import. |
| polylogue/repository.py | Adds repository facade around persist_document() for consistent persistence call sites. |
| polylogue/results.py | Adds OperationSummary and summary aggregation helper for import/sync/render flows. |
| polylogue/search.py | Adds FTS5 search execution with provider/slug/branch/model/date/attachment filtering. |
| polylogue/settings.py | Makes reset_settings() optionally target an injected Settings instance (testability). |
| polylogue/ui.py | Adds richer UI abstraction, detects missing gum/skim, and changes subprocess invocation patterns. |
| polylogue/util.py | Adds XDG path helpers, StateStore abstraction, DiffTracker/RunAccumulator, pruning/state changes, and updates delta diff invocation. |
| pyproject.toml | Adds required deps (tiktoken/qdrant-client) + dev/test tooling config (pytest/coverage/mypy). |
| tests/conftest.py | Adds a tiktoken stub for deterministic token counting in tests. |
| tests/test_automation_snippets.py | Updates automation expectations for new sync <provider> commands and module invocation. |
| tests/test_branch_and_search.py | Adds coverage for branch explorer and FTS search filtering. |
| tests/test_cli_flags.py | Adds coverage for tri-state --html parsing and sync dispatch. |
| tests/test_cli_wrappers.py | Adds coverage for CLI wrapper dispatch, JSON output, and watch delegation. |
| tests/test_codex_importer.py | Updates tests for new attachment/output layout and isolates XDG state in tests. |
| tests/test_commands_logic.py | Updates render/sync expectations for new output layout; adds prune CLI test. |
| tests/test_doctor.py | Adds tests for state/db pruning and managed-dir attachment cleanup safety. |
| tests/test_document_store_cleanup.py | Adds tests for attachment/HTML cleanup behavior in persistence. |
| tests/test_drive_client.py | Adds tests for env-based Drive credentials resolution/copying. |
| tests/test_html.py | Adds tests for escaping in HTML output and branch explorer HTML. |
| tests/test_importers_security.py | Adds tests for safe zip extraction blocking path traversal. |
| tests/test_local_sync.py | Updates local sync tests for new output layout and directory pruning behavior. |
| tests/test_pipeline.py | Adds tests for pipeline attachment download/remote-link behavior. |
| tests/test_results.py | Adds tests for OperationSummary line formatting and extra counts. |
| tests/test_stats.py | Updates stats test inputs for new output layout. |
| tests/test_status.py | Updates provider/command aggregation expectations for new sync drive naming. |
| tests/test_ui.py | Updates UI summary test behavior around gum invocation. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| result = subprocess.run( | ||
| [ | ||
| "gum", | ||
| "style", | ||
| "--border", | ||
| "rounded", | ||
| "--margin", | ||
| "1", | ||
| "--padding", | ||
| "1", | ||
| body, | ||
| ], | ||
| check=True, | ||
| stdout=subprocess.PIPE, | ||
| stderr=subprocess.PIPE, | ||
| text=True, | ||
| ) |
There was a problem hiding this comment.
banner() runs gum style with check=True and without any error handling. If gum exits non-zero (or is unexpectedly missing at runtime), this will raise and crash the CLI instead of falling back to plain output. Consider using check=False (or catching FileNotFoundError/CalledProcessError) and falling back to printing body.
| result = subprocess.run( | ||
| ["gum", "format"], | ||
| input=f"## {title}\n{text}\n", | ||
| text=True, | ||
| stdout=subprocess.PIPE, | ||
| stderr=subprocess.PIPE, | ||
| check=True, | ||
| ) | ||
| if result.stdout.strip(): | ||
| self.console.print(result.stdout.rstrip()) | ||
| return | ||
| renderable = Text(text) if Text is not None else text | ||
| self.console.print(Panel(renderable, title=title)) |
There was a problem hiding this comment.
summary() runs gum format with check=True and no fallback path on subprocess failure. A non-zero exit (e.g., user abort / gum error) will raise CalledProcessError and break command execution; catching subprocess errors (and falling back to Rich panel/plain text) would make summaries resilient.
| def choose(self, prompt: str, options: List[str]) -> Optional[str]: | ||
| if not options: | ||
| return None | ||
| if self.plain: | ||
| return options[0] | ||
| try: | ||
| result = subprocess.run( | ||
| ["gum", "choose", "--header", prompt, *options], | ||
| check=False, | ||
| stdout=subprocess.PIPE, | ||
| text=True, | ||
| ) | ||
| choice = result.stdout.strip() | ||
| return choice or None | ||
| except Exception: | ||
| return options[0] | ||
| self._warn_plain("selection") | ||
| return None |
There was a problem hiding this comment.
In plain mode, choose() now returns None even though _warn_plain() says it is "using defaults". Several call sites treat None as "cancel"; returning options[0] (like prior behavior) would provide a deterministic default and better match the warning message.
| def write_delta_diff(old_path: Path, new_path: Path, *, suffix: str = ".diff.txt") -> Optional[Path]: | ||
| if not old_path.exists() or not new_path.exists(): | ||
| return None | ||
| diff_path = new_path.with_suffix(new_path.suffix + suffix) | ||
| try: | ||
| result = subprocess.run( | ||
| ["delta", str(old_path), str(new_path)], | ||
| capture_output=True, | ||
| text=True, | ||
| check=False, | ||
| ) | ||
| result = subprocess.run( | ||
| ["delta", str(old_path), str(new_path)], | ||
| capture_output=True, | ||
| text=True, | ||
| check=False, | ||
| ) |
There was a problem hiding this comment.
write_delta_diff() no longer handles FileNotFoundError when delta is not installed. This makes --diff paths crash hard outside the Nix environment. Consider catching FileNotFoundError (and falling back to the unified_diff implementation) so diff output remains optional.
| if self.ui.plain: | ||
| raise SystemExit( | ||
| "Missing credentials.json. Download a Google OAuth client secret and place it next to polylogue.py." | ||
| "Missing credentials.json. Set ${DRIVE_CREDENTIAL_ENV} or download a Google OAuth client secret and place it next to polylogue.py." | ||
| ) | ||
| return self._prompt_for_credentials() |
There was a problem hiding this comment.
The plain-mode credentials error message uses the literal ${DRIVE_CREDENTIAL_ENV} instead of the actual env var name (e.g., POLYLOGUE_DRIVE_CREDENTIALS). Using an f-string (or hardcoding the constant) would make the guidance actionable for users.
| pyperclip | ||
| watchfiles | ||
| tiktoken | ||
| "qdrant-client" |
There was a problem hiding this comment.
pythonEnv includes "qdrant-client" as a string literal inside with ps; [ ... ]. withPackages expects package derivations; this will fail evaluation. Use the actual attribute (likely ps."qdrant-client") instead of a string.
| "qdrant-client" | |
| ps."qdrant-client" |
| except FileNotFoundError as exc: | ||
| raise RuntimeError("Required command 'sk' is not available in PATH.") from exc |
There was a problem hiding this comment.
sk_select() raises RuntimeError when sk is missing, but callers like choose_single_entry() assume the picker returns None when skim is unavailable/cancelled. Either keep the previous None behavior for missing sk, or catch this RuntimeError in choose_single_entry() and treat it as (None, True).
| except FileNotFoundError as exc: | |
| raise RuntimeError("Required command 'sk' is not available in PATH.") from exc | |
| except FileNotFoundError: | |
| return None |
| if not ui.plain: | ||
| result = subprocess.run( | ||
| ["gum", "format"], | ||
| input=f"```\n{tree}\n```", | ||
| text=True, | ||
| stdout=subprocess.PIPE, | ||
| stderr=subprocess.PIPE, | ||
| check=True, | ||
| ) | ||
| output = result.stdout.strip() | ||
| if output: | ||
| ui.console.print(output) | ||
| else: | ||
| ui.console.print(tree) |
There was a problem hiding this comment.
Several gum subprocess calls use check=True (e.g., formatting the tree output). If gum exits non-zero (or the user aborts), this will raise and terminate inspect branches rather than falling back to printing the raw tree. Consider check=False (or catching CalledProcessError) and using a plain fallback.
| ui.console.print("[cyan]No diff to display.") | ||
| return | ||
| if not ui.plain: | ||
| subprocess.run(["gum", "pager"], input=diff_text, text=True, check=True) |
There was a problem hiding this comment.
_display_diff() uses gum pager with check=True. If the pager exits non-zero (e.g., user quits/interrupts), this will raise and crash the inspect flow. Using check=False (or catching CalledProcessError) would avoid aborting the command after showing a diff.
| subprocess.run(["gum", "pager"], input=diff_text, text=True, check=True) | |
| subprocess.run(["gum", "pager"], input=diff_text, text=True, check=False) |
…t paths (#16) Decompose the 1835-line polylogue/cli.py into a polylogue/cli/ package with focused submodules, migrate all hardcoded paths to XDG base directories, switch per-conversation output from flat files to directory layout, and add branch exploration plus FTS5 search surfaces. CLI package decomposition (polylogue/cli/): - app.py: parser, main(), interactive_menu, inspect commands, prune - context.py: shared defaults, HTML tri-state resolution, settings init - sync.py: Drive/Codex/Claude Code sync with unified dispatch - imports.py: ChatGPT/Claude/Codex/Claude Code import wrappers - render.py: render command and clipboard copy helper - watch.py: provider-agnostic file watcher with debounce - status.py: status dashboard and stats aggregation - doctor.py: health check with state/database pruning - automation_cli.py: systemd/cron snippet generation - summaries.py: OperationSummary via results.py for import output Command surface redesign: - sync-codex / sync-claude-code / sync → sync codex|claude-code|drive - stats → inspect stats; new inspect branches and inspect search - --html flag changes from boolean to tri-state on|off|auto - new prune command removes legacy flat-file outputs - automation_targets.json updated for new command syntax XDG and path migration (polylogue/util.py, config.py): - CONFIG_HOME, DATA_HOME, CACHE_HOME, STATE_HOME derived from XDG vars - /realm/data/chatlog/ replaced with $XDG_DATA_HOME/polylogue/archive - _attachments/ directories renamed to attachments/ - slug.md layout becomes slug/conversation.md with slug/attachments/ - CODEX_SESSIONS_ROOT, CLAUDE_CODE_PROJECT_ROOT env-overridable New domain modules: - branch_explorer.py: tree rendering, HTML explorer, unified diff - search.py: FTS5 query execution with provider/model/date/attachment filters and skim-driven preview picker - pipeline.py: ChatContext and build_document_from_chunks extracted from commands.py; attachment collection with mtime-aware re-download - repository.py: ConversationRepository facade over document_store - results.py: OperationSummary aggregation replacing inline summaries Infrastructure hardening: - util.py: StateStore with mutate() for atomic state updates; DiffTracker and RunAccumulator replace ad-hoc snapshot management - commands.py: RunSummaryEntry/ProviderSummaryEntry replace nested dicts; _persist_conversation centralises write+diff+state - document_store.py: content hash now covers metadata; stale attachment cleanup; HTML removal when disabled - index.py: IndexBackend protocol with SqliteBackend, QdrantBackend, NullBackend behind POLYLOGUE_INDEX_BACKEND env switch - importers/utils.py: safe_extractall blocks zip path traversal - html.py: template/renderer caching; markupsafe.escape for XSS Nix packaging (flake.nix, nix/devshell.nix): - re2 overlay extracted to module-level binding - cliDeps (gum, skim, delta, git) bundled via makeWrapper - tiktoken and qdrant-client added to baseDeps - checkPhase sets XDG_STATE_HOME/XDG_CACHE_HOME for isolation - devshell gains pytest, pytest-cov, coverage, mypy, types-requests Testing: - conftest.py: tiktoken stub for deterministic token counts - new test files: branch_and_search, cli_flags, cli_wrappers, document_store_cleanup, drive_client, importers_security, pipeline, results - pyproject.toml: pytest/coverage/mypy configuration added
|
Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.
Only the rows listed above are dispositioned. Held findings remain open. |
|
Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.
Only the rows listed above are dispositioned. Held findings remain open. |
Summary
The single-file CLI (
polylogue/cli.py, 1835 lines) is decomposed into apolylogue/cli/package with eleven focused modules. Every hardcoded path is replaced with XDG base directory lookups, the per-conversation output layout migrates from flat files to directories, and two new inspection commands (inspect branches,inspect search) land as first-class CLI surfaces.Motivation
The old CLI module had become the project's junk drawer: sync logic for three providers, four import flows, the interactive menu, automation snippet generation, stats aggregation, and the doctor command all lived in one file. Adding the branch explorer and search features would have pushed it past 2500 lines with no clean separation of concerns.
Separately, every output path was rooted at
/realm/data/chatlog/, which is a personal NixOS mount point that doesn't exist on any other machine. The_attachments/naming convention also conflicted with tools that treat underscore-prefixed directories specially (Jekyll, some static site generators).I considered splitting by "concern" (commands vs. rendering vs. state) but settled on splitting by "CLI surface" instead — each subcommand family gets its own module, with shared defaults in
context.py. This keeps the import graph shallow and makes it obvious where to add flags for a given command.CLI architecture
The new package layout:
Each module imports from the domain layer (
commands.py,pipeline.py, etc.) rather than reaching across to other CLI modules.context.pyowns all the computed defaults so no two modules independently readCONFIG.defaults.Command surface changes
The top-level sync commands collapse into a single
sync <provider>with a positional argument:The
--htmlflag changes from a boolean to a tri-state (on|off|auto) so automation scripts can explicitly disable HTML without knowing the config default, while interactive users get auto-detection from their settings.New commands:
inspect branches— tree view, HTML explorer, unified diff against canonicalinspect search— FTS5 query with provider/model/date/attachment filtersinspect stats— relocated from top-levelstatsprune— removes legacyslug.md+slug_attachments/left by older releasesXDG and output layout
All default paths derive from XDG base directories:
CONFIG_HOME~/.config/polylogueDATA_HOME~/.local/share/polylogueSTATE_HOME~/.local/state/polylogueCACHE_HOME~/.cache/polylogueThe archive root moves from
/realm/data/chatlog/to$XDG_DATA_HOME/polylogue/archive, overridable viaPOLYLOGUE_ARCHIVE_ROOT.Per-conversation output migrates from flat files to directories:
This layout naturally groups conversation artifacts and makes branch directories siblings of the canonical transcript.
Extracted domain modules
pipeline.py—ChatContextandbuild_document_from_chunks()extracted fromcommands.py. The attachment collector checks remotemodifiedTimeagainst local mtime before re-downloading, which avoids redundant Drive API calls on incremental syncs.repository.py— thin facade overdocument_store.persist_document()so callers (commands.py, conversation.py) share a single entry point with consistent signatures.results.py—OperationSummaryreplaces the inline summary-building logic that was duplicated across sync, import, and render.summarize_import_results()aggregates attachments, tokens, words, diffs, and branches into a single object with a.lines()method for display.search.py— executes FTS5 queries against themessages_ftsvirtual table, applying provider/slug/branch/model/date/attachment filters. Post-filter on timestamp and model happens in Python because SQLite FTS5 doesn't support those natively in the MATCH clause.branch_explorer.py— loads branch metadata from SQLite, renders ASCII trees, generates themed HTML explorers, and computes unified diffs between branches.Infrastructure changes
StateStorein util.py replaces the load/save pattern with amutate(fn)method that reads, applies a function, and writes atomicallyDiffTrackerencapsulates the snapshot-before/diff-after pattern that was repeated in every commandRunAccumulatorreplacesdefaultdict(int)totals scattered across render, sync, and importdocument_store.py: content hash now includes metadata (excluding the hash itself), so metadata-only changes are detected; stale attachments are cleaned up on re-persist; HTML files are removed when HTML is disabledindex.py:IndexBackendprotocol with three implementations behindPOLYLOGUE_INDEX_BACKENDsafe_extractallin importers/utils.py validates every zip member path against the target directory to block path traversalhtml.py: Jinja template and markdown-it renderer are cached at module level; all user-supplied content passes throughmarkupsafe.escapeNix packaging
The flake extracts
re2Overlayto a top-level binding, addscliDeps(gum, skim, delta, git) as both build and check inputs, and wraps the installed binary withmakeWrapperso CLI tools are always on PATH. The check phase setsXDG_STATE_HOMEandXDG_CACHE_HOMEto$TMPDIRso tests don't pollute the builder's home directory.tiktokenandqdrant-clientare added tobaseDeps.Testing
Eight new test files cover the branch explorer, search filtering, CLI flag parsing, CLI wrapper dispatch, document store cleanup, Drive credential env detection, zip path traversal blocking, and the pipeline attachment collector. A
tiktokenstub in conftest.py provides deterministic word-split tokenization so tests don't need the real BPE model.pyproject.tomlgains pytest, coverage, and mypy configuration.