Skip to content

refactor: split monolithic CLI into command modules with XDG-compliant paths - #16

Closed
Sinity wants to merge 14 commits into
masterfrom
feature/cli/xdg-modules-inspect
Closed

Sinity wants to merge 14 commits into
masterfrom
feature/cli/xdg-modules-inspect

Conversation

@Sinity

@Sinity Sinity commented Apr 7, 2026 •

Copy link
Copy Markdown
Owner

Summary

The single-file CLI (polylogue/cli.py, 1835 lines) is decomposed into a polylogue/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:

polylogue/cli/
├── __init__.py          # public API shim for backwards compat
├── app.py               # parser, main(), interactive menu, inspect commands
├── context.py           # defaults, HTML resolution, settings helpers
├── sync.py              # sync drive|codex|claude-code
├── imports.py           # import chatgpt|claude|codex|claude-code
├── render.py            # render command + clipboard helper
├── watch.py             # provider-agnostic watcher
├── status.py            # status dashboard + stats
├── doctor.py            # health checks
├── automation_cli.py    # systemd/cron snippets
└── summaries.py         # OperationSummary bridge to results.py

Each module imports from the domain layer (commands.py, pipeline.py, etc.) rather than reaching across to other CLI modules. context.py owns all the computed defaults so no two modules independently read CONFIG.defaults.

Command surface changes

The top-level sync commands collapse into a single sync <provider> with a positional argument:

# Before                              # After
polylogue sync-codex --html           polylogue sync codex --html
polylogue sync-claude-code --prune    polylogue sync claude-code --prune
polylogue sync --folder-name X        polylogue sync drive --folder-name X

The --html flag 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 canonical
  • inspect search — FTS5 query with provider/model/date/attachment filters
  • inspect stats — relocated from top-level stats
  • prune — removes legacy slug.md + slug_attachments/ left by older releases

XDG and output layout

All default paths derive from XDG base directories:

Variable Default
CONFIG_HOME ~/.config/polylogue
DATA_HOME ~/.local/share/polylogue
STATE_HOME ~/.local/state/polylogue
CACHE_HOME ~/.cache/polylogue

The archive root moves from /realm/data/chatlog/ to $XDG_DATA_HOME/polylogue/archive, overridable via POLYLOGUE_ARCHIVE_ROOT.

Per-conversation output migrates from flat files to directories:

# Before                      # After
out/my-chat.md                out/my-chat/conversation.md
out/my-chat_attachments/      out/my-chat/attachments/
out/my-chat.html              out/my-chat/conversation.html
                              out/my-chat/branches/branch-001/branch-001.md

This layout naturally groups conversation artifacts and makes branch directories siblings of the canonical transcript.

Extracted domain modules

pipeline.py — ChatContext and build_document_from_chunks() extracted from commands.py. The attachment collector checks remote modifiedTime against local mtime before re-downloading, which avoids redundant Drive API calls on incremental syncs.

repository.py — thin facade over document_store.persist_document() so callers (commands.py, conversation.py) share a single entry point with consistent signatures.

results.py — OperationSummary replaces 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 the messages_fts virtual 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

  • StateStore in util.py replaces the load/save pattern with a mutate(fn) method that reads, applies a function, and writes atomically
  • DiffTracker encapsulates the snapshot-before/diff-after pattern that was repeated in every command
  • RunAccumulator replaces defaultdict(int) totals scattered across render, sync, and import
  • document_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 disabled
  • index.py: IndexBackend protocol with three implementations behind POLYLOGUE_INDEX_BACKEND
  • safe_extractall in importers/utils.py validates every zip member path against the target directory to block path traversal
  • html.py: Jinja template and markdown-it renderer are cached at module level; all user-supplied content passes through markupsafe.escape

Nix packaging

The flake extracts re2Overlay to a top-level binding, adds cliDeps (gum, skim, delta, git) as both build and check inputs, and wraps the installed binary with makeWrapper so CLI tools are always on PATH. The check phase sets XDG_STATE_HOME and XDG_CACHE_HOME to $TMPDIR so tests don't pollute the builder's home directory. tiktoken and qdrant-client are added to baseDeps.

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 tiktoken stub in conftest.py provides deterministic word-split tokenization so tests don't need the real BPE model. pyproject.toml gains pytest, coverage, and mypy configuration.

@Sinity Sinity added type:refactor Code restructuring area:cli CLI area:pipeline Pipeline area:storage Storage area:schema Schema labels Apr 7, 2026
Copilot AI review requested due to automatic review settings April 7, 2026 11:42
@coderabbitai

coderabbitai Bot commented Apr 7, 2026 •

Copy link
Copy Markdown

Caution

Review failed

Failed to post review comments

📝 Walkthrough

Walkthrough

Replaces the monolithic CLI with a modular cli package and new entrypoint, consolidates provider sync/import subcommands, moves conversation outputs to per-slug directories (conversation.md + attachments/), adds branch exploration and FTS search, adopts XDG paths, hardens ZIP/attachment handling, and updates build/dev tooling and tests.

Changes

Cohort / File(s) Summary
CLI rework
polylogue/cli.py (deleted), polylogue/cli/__init__.py, polylogue/cli/app.py, polylogue/cli/sync.py, polylogue/cli/imports.py, polylogue/cli/render.py, polylogue/cli/watch.py, polylogue/cli/status.py, polylogue/cli/doctor.py, polylogue/cli/automation_cli.py, polylogue/cli/context.py, polylogue/cli/summaries.py
Removed monolithic CLI and added a modular cli package: new top-level parser, interactive menu, provider-agnostic sync/import/render/watch flows, inspect/prune/automation commands, context/default helpers, and re-export shim.
Storage & persistence pipeline
polylogue/document_store.py, polylogue/conversation.py, polylogue/repository.py, polylogue/pipeline.py, polylogue/local_sync.py, polylogue/commands.py, polylogue/options.py, polylogue/results.py
Centralized document build/persistence via ConversationRepository and pipeline; output layout changed to <slug>/conversation.md, attachments/, optional conversation.html; added DiffTracker, RunAccumulator, new dataclasses and slug fields.
Branching & search
polylogue/branch_explorer.py, polylogue/search.py, polylogue/branching.py
New branch-graph model and presentation, ASCII/HTML branch explorer, branch diffs, and SQLite FTS-backed search with filters and result normalization.
Importers & ZIP safety
polylogue/importers/..., polylogue/importers/utils.py, polylogue/importers/base.py
Importers now write per-slug directories with attachments/; added safe ZIP extraction, filename sanitization, deterministic naming, and made ImportResult.slug required; tokenization now requires tiktoken.
Drive & indexing
polylogue/drive.py, polylogue/drive_client.py, polylogue/index.py, polylogue/index_qdrant.py
Hardened Drive retry/escaping and credential sourcing (env var support); introduced index backend abstraction (Sqlite/Qdrant/Null) with stricter qdrant error handling.
UI, HTML, cli-common
polylogue/ui.py, polylogue/html.py, polylogue/cli_common.py
Added ConsoleLike typing, plain-mode warnings, cached Markdown/Jinja renderer, safer HTML escaping, and adjusted selection/prune helpers and external-tool behavior.
Config, state & utils
polylogue/config.py, polylogue/util.py, polylogue/settings.py
Switched to XDG-based config/data/state roots, introduced StateStore, path ordering helper, DiffTracker/RunAccumulator, updated defaults and settings reset behavior.
Automation & tooling
polylogue/automation.py, polylogue/automation_targets.json, flake.nix, nix/devshell.nix, pyproject.toml
Automation snippets updated to invoke python -m polylogue.cli and tokenized ["sync","<provider>"] commands; Nix/devshell and pyproject updated with tiktoken, qdrant-client, and dev/test tooling.
Docs
AGENTS.md, README.md, docs/providers/*
Docs updated for new CLI forms, per-conversation attachments/ paths, branch-aware layout, and moved sample inputs/walkthrough pointers into docs/providers/.
Tests
tests/* (many new/updated tests)
Large test additions and updates covering CLI flags/dispatch, branch/search, pipeline attachment download behavior, ZIP safety, doctor pruning, Drive credential env handling, and updated layout/command expectations.

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
Loading

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Possibly related issues

Poem

🐰 I hopped through folders, tidy and bright,
Slugs now nestle in their own soft site.
Commands aligned, subcommands take flight,
Branch trees bloom and search finds light.
XDG trails glowing — hopping feels right!

✨ 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/cli/xdg-modules-inspect
⚔️ Resolve merge conflicts
  • Resolve merge conflict in branch feature/cli/xdg-modules-inspect

Sinity added a commit that referenced this pull request Apr 7, 2026
…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

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 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".

Comment thread polylogue/cli/app.py Resolved
Comment thread polylogue/util.py Resolved

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

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 in cli/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.

Comment thread polylogue/ui.py
Comment on lines +75 to +91
result = subprocess.run(
[
"gum",
"style",
"--border",
"rounded",
"--margin",
"1",
"--padding",
"1",
body,
],
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)

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.

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.

Copilot uses AI. Check for mistakes.
Comment thread polylogue/ui.py
Comment on lines +103 to 115
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))

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.

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.

Copilot uses AI. Check for mistakes.
Comment thread polylogue/ui.py
Comment on lines 128 to +133
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

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.

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.

Copilot uses AI. Check for mistakes.
Comment thread polylogue/util.py
Comment on lines 424 to +433
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,
)

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.

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.

Copilot uses AI. Check for mistakes.
Comment thread polylogue/drive_client.py
Comment on lines 48 to +52
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()

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

Copilot uses AI. Check for mistakes.
Comment thread nix/devshell.nix
pyperclip
watchfiles
tiktoken
"qdrant-client"

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.

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.

Suggested change
"qdrant-client"
ps."qdrant-client"

Copilot uses AI. Check for mistakes.
Comment thread polylogue/cli_common.py
Comment on lines +91 to +92
except FileNotFoundError as exc:
raise RuntimeError("Required command 'sk' is not available in PATH.") from exc

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.

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).

Suggested change
except FileNotFoundError as exc:
raise RuntimeError("Required command 'sk' is not available in PATH.") from exc
except FileNotFoundError:
return None

Copilot uses AI. Check for mistakes.
Comment thread polylogue/cli/app.py
Comment on lines +203 to +216
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)

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.

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.

Copilot uses AI. Check for mistakes.
Comment thread polylogue/cli/app.py
ui.console.print("[cyan]No diff to display.")
return
if not ui.plain:
subprocess.run(["gum", "pager"], input=diff_text, text=True, check=True)

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.

_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.

Suggested change
subprocess.run(["gum", "pager"], input=diff_text, text=True, check=True)
subprocess.run(["gum", "pager"], input=diff_text, text=True, check=False)

Copilot uses AI. Check for mistakes.
Repository owner deleted a comment from coderabbitai Bot Apr 7, 2026
Repository owner deleted a comment from coderabbitai Bot Apr 7, 2026
Repository owner deleted a comment from coderabbitai Bot Apr 7, 2026
Repository owner deleted a comment from coderabbitai Bot Apr 7, 2026
@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/cli/xdg-modules-inspect branch April 9, 2026 23:02
Sinity added a commit that referenced this pull request Apr 22, 2026
…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
@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

Only the rows listed above are dispositioned. Held findings remain open.

@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

Only the rows listed above are dispositioned. Held findings remain open.

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

Labels

area:cli CLI 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