Skip to content

refactor: remove argparse wrappers and make Click primary - #38

Closed
Sinity wants to merge 8 commits into
masterfrom
feature/cli/click-consolidation-and-redaction
Closed

Sinity wants to merge 8 commits into
masterfrom
feature/cli/click-consolidation-and-redaction

Conversation

@Sinity

@Sinity Sinity commented Apr 7, 2026 •

Copy link
Copy Markdown
Owner

Summary

I removed the last argparse compatibility layer and made the Click tree the only dispatch path, then used that cleanup to land two option-plumbing changes that had been awkward under the dual stack: redacted output writes and raw-hash-based local sync skips. The important architectural change is not just that polylogue/cli/app.py disappears; it is that command callbacks in polylogue/cli/click_app.py now talk directly to the real run_*_cli helpers without converting Click arguments back into argparse.Namespace objects and bouncing through dispatch() shims. That trims an entire stratum of parser builders, registry code, and helper functions that had to be kept in lockstep with the Click decorators. Once that indirection was gone, it became much simpler to thread --sanitize-html through sync/import/render and to put hash-based fast paths in the local sync pipeline without wiring every flag twice. The result is a smaller CLI core, a clearer option flow, and materially less unnecessary work during repeated local syncs.

Motivation

The branch started from a codebase that was effectively running two CLIs at the same time. polylogue/cli/click_app.py owned the public interface, but it still wrapped the older argparse world by constructing Namespace objects and forwarding them into polylogue/cli/app.py, polylogue/cli/registry.py, and the setup_parser() / dispatch() pairs under polylogue/cli/commands/. That duplication had three direct costs.

First, every new flag or command tweak had to be declared twice. A flag like --sanitize-html is a good example: if I had left the argparse layer in place, I would have needed matching Click decorators, argparse option registration, wrapper namespaces, and dispatch handling just to carry one boolean to the persistence layer.

Second, the parser split made the code harder to test. The test suite had accumulated assertions against both parser objects and command behavior, but the thing users actually exercised was the Click group. That meant a lot of churn on parser wiring that added little confidence in end-to-end behavior.

Third, local sync was still paying for coarse freshness checks. The raw import state already had hashes available, but session and export-bundle sync still leaned heavily on mtimes, so harmless touches could trigger full parse/render/persist cycles. That was especially painful for Codex and export-bundle workflows where the inputs can be large but stable.

I grouped the redaction and freshness work into the same change because they both needed the new direct option path. They are not random extras bolted onto the CLI cleanup; they are the first concrete features that benefit from removing the compatibility layer.

Changes by concern

1. Remove the argparse compatibility layer

The largest simplification is the deletion set:

  • polylogue/cli/app.py
  • polylogue/cli/registry.py
  • polylogue/cli/arg_helpers.py
  • the argparse setup_parser() / dispatch() wrappers in polylogue/cli/commands/*

In their place, polylogue/cli/click_app.py now dispatches directly into the actual command helpers:

@click.pass_obj
def sync(env: CommandEnv, **kwargs) -> None:
    from .sync import run_sync_cli
    run_sync_cli(SimpleNamespace(**kwargs), env)

That is a much more honest boundary than:

args = Namespace(**kwargs)
sync_cmd.dispatch(args, env)

because there is no hidden second parser anymore. Moved help/completion-facing introspection into Click-native helpers like click_introspect.py and completions_cli.py, so completions walk the actual command tree without reconstructing parser state from argparse subparsers.

A second-order benefit of this split is that the old monolith gets decomposed into modules that have a single reason to change: branches_cli.py, search_cli.py, compare_cli.py, config_editor.py, failure_logging.py, prune_cli.py, and path_policy.py. The CLI is still one product surface, but it no longer lives in one 1700+ line file.

2. Thread redaction through the real write path

The new polylogue/redaction.py adds sanitize_text() and centralizes the masking rules instead of sprinkling ad hoc substitutions across CLI commands. The actual behavior matters more than the regex list:

  • redaction happens before the final content hash is computed
  • the persisted metadata records that the document was redacted
  • run payloads surface the same state for automation

That makes --sanitize-html deterministic. A redacted archive is not just a raw archive with a UI flag attached; it is a distinct persisted representation with its own content hash. That choice keeps cache behavior, drift detection, and downstream comparisons coherent.

The flag is carried all the way through the real pipeline:

click_app.py → sync/import/render helpers → process_conversation() → persist_document()

Intentionally kept the redaction at the persistence boundary. Doing it earlier would have made importer behavior provider-specific; doing it later would have let metadata and hashes drift away from the actual emitted document body.

3. Skip unchanged local inputs by hash, not just mtime

The local sync changes are small in code volume but meaningful in effect. _sync_sessions() now compares the current raw import hash against the stored raw hash before reparsing the session, and _sync_export_bundles() stores a per-bundle hash so unchanged ZIPs can be skipped before the import call even runs. I kept the mtime check as a fallback rather than deleting it outright, because hashes are not always available for every legacy path.

This gives the fast path I wanted:

  • unchanged session file → no parse/render/persist cycle
  • unchanged export bundle → no import pass for the bundle
  • changed content → existing pipeline still runs as before

The key point is that freshness is tied to actual source bytes, not just filesystem metadata.

4. Preserve the operator-facing parts of the CLI

A pure deletion pass would have regressed usability, so I pulled out the useful CLI-facing bits that had been trapped in app.py. config_editor.py adds an interactive config edit path, summaries.py gets a richer render summary table, and context.py accepts plain objects instead of requiring argparse namespace semantics. These are the parts that let the Click-only surface feel complete rather than merely “less legacy”.

Testing

I shifted the CLI tests toward the public surface by using CliRunner.invoke() instead of parser-construction assertions. The most important new coverage is:

  • tests/test_redaction.py for email/token masking and the polylogue.redacted metadata stamp
  • tests/test_local_sync.py for unchanged-session and unchanged-export-bundle hash skips
  • the migrated CLI invocation tests, which now exercise the Click group directly rather than verifying argparse wrapper behavior

That testing posture matches the architectural direction of the patch: validate the surviving path, not the code that used to bridge to the removed one.

Notes

There are still internal call sites that use namespace-like option objects, but they are plain Python objects instead of argparse-specific types. I left that shape in place deliberately because it keeps command helpers lightweight and avoids introducing a premature dataclass layer for every command. The redaction support also only targets persisted Markdown/HTML bodies in this pass; it does not attempt to mutate raw imports or database source payloads. That separation keeps the archival model intact while still allowing sanitized exports when operators need them.

Summary by CodeRabbit

Release Notes

  • New Features

    • Added --sanitize-html flag to render, sync, and import commands for redacting sensitive content.
    • Added interactive config edit command for managing settings.
    • Added branches command for exploring and comparing conversation branches.
  • Improvements

    • Enhanced configuration display with additional system details.
    • Improved search and statistics command functionality.

Sinity and others added 8 commits December 12, 2025 06:20
Adds --sanitize-html to render/import/sync flows, sanitizes persisted Markdown before hashing, and records redacted runs.

Includes core redaction patterns and tests.

🤖 Generated with Codex CLI

Co-Authored-By: OpenAI Codex <[email protected]>
Adds interactive 'polylogue config edit', includes labeled roots in default scans, and expands prefs defaults (root/sanitize).

🤖 Generated with Codex CLI

Co-Authored-By: OpenAI Codex <[email protected]>
Add summarize_render helper and use it in render CLI; also apply diff/sanitize prefs consistently.

🤖 Generated with Codex CLI

Co-Authored-By: OpenAI Codex <[email protected]>
Local session sync now skips re-imports when raw hashes match, even if mtimes drift, while still re-running for dirty outputs.

🤖 Generated with Codex CLI

Co-Authored-By: OpenAI Codex <[email protected]>
Local export sync now records bundle hashes and skips reprocessing ChatGPT/Claude exports when unchanged (unless pruning).

🤖 Generated with Codex CLI

Co-Authored-By: OpenAI Codex <[email protected]>
- Route app/main/help/completions through Click.
- Add optional-value Click option for --html ("--html" => on, "--html off").
- Switch completion engine to introspect Click commands.
- Fix search dispatcher import + Click naming collisions.
- Update CLI tests to use Click runner.

🤖 Generated with Codex CLI

Co-Authored-By: OpenAI Codex <[email protected]>
Document the Click-first entrypoint and treat argparse setup_parser as legacy.

🤖 Generated with Codex CLI

Co-Authored-By: OpenAI Codex <[email protected]>
- Switch CLI helpers to SimpleNamespace-based args\n- Extract completions, search/compare/branches/prune helpers\n- Delete legacy argparse entrypoint and commands modules\n- Update tests to target Click CLI\n\n🤖 Generated with Codex CLI\n\nCo-Authored-By: OpenAI Codex <[email protected]>
Copilot AI review requested due to automatic review settings April 7, 2026 12:29
@Sinity Sinity added type:refactor Code restructuring area:cli CLI area:pipeline Pipeline area:storage Storage labels Apr 7, 2026
"runsDb": str(env.database.resolve_path()),
}
)
print(json.dumps(payload))
@coderabbitai

coderabbitai Bot commented Apr 7, 2026 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

@Sinity has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 11 minutes and 6 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 11 minutes and 6 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 30fb888f-9b59-4477-a7c8-e63dec3a2ab7

📥 Commits

Reviewing files that changed from the base of the PR and between eb489c6 and c11c428.

📒 Files selected for processing (78)
  • polylogue/cli/__init__.py
  • polylogue/cli/__main__.py
  • polylogue/cli/app.py
  • polylogue/cli/arg_helpers.py
  • polylogue/cli/attachments.py
  • polylogue/cli/branches_cli.py
  • polylogue/cli/browse.py
  • polylogue/cli/click_app.py
  • polylogue/cli/click_introspect.py
  • polylogue/cli/click_options.py
  • polylogue/cli/commands/README.md
  • polylogue/cli/commands/__init__.py
  • polylogue/cli/commands/attachments.py
  • polylogue/cli/commands/browse.py
  • polylogue/cli/commands/config.py
  • polylogue/cli/commands/import_cmd.py
  • polylogue/cli/commands/maintain.py
  • polylogue/cli/commands/render.py
  • polylogue/cli/commands/search.py
  • polylogue/cli/commands/status.py
  • polylogue/cli/commands/sync.py
  • polylogue/cli/compare_cli.py
  • polylogue/cli/completion_engine.py
  • polylogue/cli/completions_cli.py
  • polylogue/cli/config_cli.py
  • polylogue/cli/config_editor.py
  • polylogue/cli/context.py
  • polylogue/cli/doctor.py
  • polylogue/cli/env_cli.py
  • polylogue/cli/examples.py
  • polylogue/cli/failure_logging.py
  • polylogue/cli/imports.py
  • polylogue/cli/inbox.py
  • polylogue/cli/index_cli.py
  • polylogue/cli/init.py
  • polylogue/cli/maintain.py
  • polylogue/cli/open_helper.py
  • polylogue/cli/path_policy.py
  • polylogue/cli/prefs.py
  • polylogue/cli/prune_cli.py
  • polylogue/cli/registry.py
  • polylogue/cli/render.py
  • polylogue/cli/runs.py
  • polylogue/cli/search_cli.py
  • polylogue/cli/settings_cli.py
  • polylogue/cli/status.py
  • polylogue/cli/summaries.py
  • polylogue/cli/sync.py
  • polylogue/cli/watch.py
  • polylogue/commands.py
  • polylogue/conversation.py
  • polylogue/document_store.py
  • polylogue/importers/chatgpt.py
  • polylogue/importers/claude_ai.py
  • polylogue/importers/claude_code.py
  • polylogue/importers/codex.py
  • polylogue/local_sync.py
  • polylogue/options.py
  • polylogue/redaction.py
  • tests/test_cli_error_messages.py
  • tests/test_cli_flags.py
  • tests/test_cli_help_env.py
  • tests/test_cli_integration.py
  • tests/test_cli_wrappers.py
  • tests/test_commands_logic.py
  • tests/test_consolidated_commands.py
  • tests/test_env_cli.py
  • tests/test_failure_logging.py
  • tests/test_inbox_cli.py
  • tests/test_index_cli.py
  • tests/test_local_sync.py
  • tests/test_redaction.py
  • tests/test_runs_cli.py
  • tests/test_search_open.py
  • tests/test_settings_cli.py
  • tests/test_stats.py
  • tests/test_status.py
  • tests/test_watch_cli.py
📝 Walkthrough

Walkthrough

The pull request performs a comprehensive migration of the CLI architecture from argparse-based command dispatching to Click-based commands, while introducing HTML sanitization throughout the import/sync/render pipelines and hash-based content skipping for local sync operations.

Changes

Cohort / File(s) Summary
CLI Architecture Overhaul
polylogue/cli/__init__.py, polylogue/cli/__main__.py, polylogue/cli/click_app.py, polylogue/cli/click_introspect.py, polylogue/cli/click_options.py
Removed legacy argparse re-exports from init; added Click-based app entry point via main.py; replaced argparse-based help/completion logic with Click introspection; added OptionalValueChoiceOption for flexible flag handling.
Removed Legacy Argparse Infrastructure
polylogue/cli/app.py, polylogue/cli/arg_helpers.py, polylogue/cli/registry.py, polylogue/cli/commands/*
Deleted entire argparse-based dispatcher, argument helpers, command registry, and command module definitions (attachments, browse, config, import_cmd, maintain, render, search, status, sync).
New Click-Based Command Modules
polylogue/cli/branches_cli.py, polylogue/cli/completions_cli.py, polylogue/cli/compare_cli.py, polylogue/cli/config_cli.py, polylogue/cli/config_editor.py, polylogue/cli/env_cli.py, polylogue/cli/prune_cli.py, polylogue/cli/search_cli.py
Implemented standalone CLI command handlers replacing old argparse dispatchers; replaces commands/modules pattern with direct Click integration and SimpleNamespace-based argument passing.
Shared CLI Utilities
polylogue/cli/failure_logging.py, polylogue/cli/path_policy.py, polylogue/cli/summaries.py
Added failure recording with exit-reason classification, path validation/creation policies, and render result summarization.
Type Migration to SimpleNamespace
polylogue/cli/attachments.py, polylogue/cli/browse.py, polylogue/cli/context.py, polylogue/cli/doctor.py, polylogue/cli/env_cli.py, polylogue/cli/inbox.py, polylogue/cli/imports.py, polylogue/cli/index_cli.py, polylogue/cli/init.py, polylogue/cli/maintain.py, polylogue/cli/open_helper.py, polylogue/cli/prefs.py, polylogue/cli/render.py, polylogue/cli/runs.py, polylogue/cli/settings_cli.py, polylogue/cli/status.py, polylogue/cli/sync.py, polylogue/cli/watch.py
Replaced argparse.Namespace type annotations with types.SimpleNamespace across all CLI handlers; loosened types to object for generic option access via getattr.
HTML Sanitization Feature
polylogue/redaction.py, polylogue/options.py, polylogue/conversation.py, polylogue/document_store.py, polylogue/importers/chatgpt.py, polylogue/importers/claude_ai.py, polylogue/importers/claude_code.py, polylogue/importers/codex.py, polylogue/commands.py, polylogue/cli/render.py, polylogue/cli/imports.py, polylogue/cli/sync.py, polylogue/cli/watch.py
Added sanitize_html boolean parameter and sanitize_text() redaction function to mask secrets; propagated through importers, sync/render command pipelines, and persistence layer; included in telemetry payloads.
Hash-Based Content Skipping
polylogue/local_sync.py, polylogue/options.py
Implemented content-hash comparison for sessions and export bundles to skip processing when source unchanged; stores registrar state with bundle metadata for quick skip detection.
Test Suite Refactoring
tests/test_cli_error_messages.py, tests/test_cli_flags.py, tests/test_cli_help_env.py, tests/test_cli_integration.py, tests/test_cli_wrappers.py, tests/test_commands_logic.py, tests/test_consolidated_commands.py, tests/test_env_cli.py, tests/test_failure_logging.py, tests/test_inbox_cli.py, tests/test_index_cli.py, tests/test_local_sync.py, tests/test_redaction.py, tests/test_runs_cli.py, tests/test_search_open.py, tests/test_settings_cli.py, tests/test_stats.py, tests/test_status.py, tests/test_watch_cli.py
Migrated from argparse-based parser testing to Click's CliRunner; replaced Namespace with SimpleNamespace; updated mocking targets and assertions; added redaction/sanitization test coverage; enhanced local sync tests for skip verification.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related issues

Poem

🐰 From argparse burrows to Click's bright light,
Old dispatchers fade, new commands take flight!
Secrets are masked, hashes skip unchanged,
The CLI rebirth: refactored and arranged!
SimpleNamespace hops where Namespace stood—
Polylogue's foundation: cleaner than ever, it's good!

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 11.27% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The PR title clearly and concisely summarizes the main architectural change: removing argparse compatibility and making Click the primary CLI dispatch mechanism.
Description check ✅ Passed The PR description is comprehensive and well-structured, covering summary, motivation, changes by concern, testing approach, and implementation notes. All key sections are present and detailed.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/cli/click-consolidation-and-redaction

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

Sinity added a commit that referenced this pull request Apr 7, 2026
…#38)

Delete the 1786-line monolithic `app.py`, the entire `cli/commands/`
argparse wrapper directory, `arg_helpers.py`, and `registry.py`. Click
becomes the sole CLI surface, with command handlers extracted into
focused modules and all `argparse.Namespace` usage replaced by
`types.SimpleNamespace`.

CLI architecture (deletions):
- `cli/app.py`: entire argparse entrypoint, parser builder, all
  `_dispatch_*` handlers, `build_parser()`, `CommandRegistry` usage
- `cli/commands/{sync,render,config,search,status,browse,maintain,
  attachments,import_cmd}.py`: argparse `setup_parser`/`dispatch` pairs
- `cli/arg_helpers.py`: argparse parent parsers, `PathPolicy`,
  `add_*_option` helpers
- `cli/registry.py`: `CommandRegistry` class and handler map
- `docs/architecture.md`: outdated architectural overview

CLI architecture (extractions from app.py into focused modules):
- `branches_cli.py`: branch exploration (was `run_inspect_branches`)
- `search_cli.py`: search, picker, preview (was `run_inspect_search`)
- `compare_cli.py`: provider comparison (was `run_compare_cli`)
- `completions_cli.py`: shell completion scripts and `_complete`
- `config_cli.py`: `config show` handler
- `config_editor.py`: new interactive `config edit` subcommand
- `prune_cli.py`: legacy file pruning (was `run_prune_cli`)
- `failure_logging.py`: `record_failure` (was `_record_failure`)
- `click_introspect.py`: `click_command_entries` for help/completions
- `click_options.py`: `OptionalValueChoiceOption` so `--html` works
  bare or with a value (`--html` → "on", `--html off` → "off")
- `path_policy.py`: `PathPolicy` + `resolve_path` from arg_helpers

Click entrypoint (`click_app.py`):
- `_should_use_plain()` moved here from app.py, now accepts keyword
  args instead of an argparse Namespace
- All command functions call `run_*_cli` directly with SimpleNamespace
  instead of routing through `*_cmd.dispatch()`
- `main()` wraps `cli.main(standalone_mode=False)` with explicit
  ClickException/Abort handling
- Completion engine rewired to walk Click's command tree instead of
  argparse subparsers

HTML redaction (`--sanitize-html`):
- New `polylogue/redaction.py` with `sanitize_text()` masking emails,
  OpenAI/Anthropic/GitHub/Slack/AWS/Google keys, and Bearer tokens
- Flag threaded through sync, import, render → `process_conversation`
  → `persist_document`, which applies redaction before computing the
  content hash and stamps `polylogue.redacted: true` in metadata
- Run payloads include `redacted: true` when the flag is active

Content-hash skip in `local_sync.py`:
- `_sync_sessions` compares the raw import hash from `raw_storage`
  against the stored hash before re-processing; skips when identical
- `_sync_export_bundles` tracks a per-bundle hash in state; unchanged
  archives skip the entire import call and increment `skipped`
- Existing mtime-based freshness check remains as a fallback

Context and summaries:
- `DEFAULT_OUTPUT_ROOTS` now collects paths from labeled roots as well
  as the base output dirs, so `prune` and `stats` cover all roots
- `summaries.py` gains `summarize_render()` with a Rich table for
  per-file token/attachment breakdown
- `resolve_html_settings` and related context functions accept plain
  objects instead of requiring argparse Namespace

Tests:
- All CLI tests migrated from argparse parser assertions to Click
  `CliRunner.invoke()` against the Click group
- New `test_redaction.py` covers email/key masking and the
  `persist_document(sanitize=True)` metadata stamp
- `test_local_sync.py` extended with content-hash skip assertions
  for both sessions and export bundles

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 completes the CLI refactor by removing the remaining argparse compatibility layer and making the Click command tree the sole dispatch path, while also plumbing --sanitize-html through persistence and adding hash-based fast paths for local sync.

Changes:

  • Removed argparse wrappers/registry and switched Click callbacks to call run_*_cli helpers directly via SimpleNamespace.
  • Added redaction support (--sanitize-html) that sanitizes persisted document bodies and marks metadata/run payloads.
  • Improved local sync performance by skipping unchanged sessions/export bundles based on content hashes (not only mtimes).

Reviewed changes

Copilot reviewed 78 out of 78 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
tests/test_watch_cli.py Switches test args from argparse Namespace to SimpleNamespace.
tests/test_status.py Removes argparse parser assertions; calls run_status_cli with SimpleNamespace.
tests/test_stats.py Updates imports/calls for stats CLI and swaps to SimpleNamespace.
tests/test_settings_cli.py Uses SimpleNamespace for settings CLI tests.
tests/test_search_open.py Updates anchor-line helper import to new search_cli module.
tests/test_runs_cli.py Uses SimpleNamespace for runs CLI tests.
tests/test_redaction.py Adds coverage for sanitize_text() and persistence redaction metadata.
tests/test_local_sync.py Adds tests for hash-based skip behavior in local sync.
tests/test_index_cli.py Uses SimpleNamespace for index CLI tests.
tests/test_inbox_cli.py Uses SimpleNamespace for inbox CLI tests.
tests/test_failure_logging.py Moves failure logging test to new failure_logging.record_failure.
tests/test_env_cli.py Updates integration test to use Click entrypoint and SimpleNamespace.
tests/test_consolidated_commands.py Migrates parser-structure assertions to Click command-tree assertions.
tests/test_commands_logic.py Updates prune CLI import path and uses SimpleNamespace.
tests/test_cli_wrappers.py Updates wrapper tests to use new search_cli and SimpleNamespace args.
tests/test_cli_integration.py Uses Click main entrypoint and SimpleNamespace args.
tests/test_cli_help_env.py Migrates help/completions/config-show tests to CliRunner.invoke() against Click CLI.
tests/test_cli_flags.py Migrates flag-parsing tests to Click invocation; updates helpers/imports accordingly.
tests/test_cli_error_messages.py Replaces argparse dispatcher error tests with Click command error behavior tests.
polylogue/redaction.py Introduces regex-based sanitization for common secrets/tokens.
polylogue/options.py Adds sanitize_html to render/sync option dataclasses.
polylogue/local_sync.py Adds sanitize plumbing and implements hash-based skip for sessions/export bundles.
polylogue/importers/codex.py Threads sanitize_html through Codex importer pipeline.
polylogue/importers/claude_code.py Threads sanitize_html through Claude Code importer pipeline.
polylogue/importers/claude_ai.py Threads sanitize_html through Claude export importer/render path.
polylogue/importers/chatgpt.py Threads sanitize_html through ChatGPT export importer/render path.
polylogue/document_store.py Adds sanitize persistence option; sanitizes body and stamps polylogue.redacted.
polylogue/conversation.py Plumbs sanitize_html into persist_document() calls via process_conversation().
polylogue/commands.py Uses new path_policy helpers and stamps run payloads with redacted when enabled.
polylogue/cli/watch.py Adds --sanitize-html to watch plan and threads flags into local sync + run logging.
polylogue/cli/sync.py Removes argparse types, adds root-label handling, watch dispatch, failure logging, redacted run payloads.
polylogue/cli/summaries.py Adds summarize_render() helper for richer render summaries.
polylogue/cli/status.py Switches to SimpleNamespace and uses new path_policy resolver for stats.
polylogue/cli/settings_cli.py Switches to SimpleNamespace-style args.
polylogue/cli/search_cli.py New Click-era search implementation (picker, open-in-editor/browser, JSON/CSV/JSONL output).
polylogue/cli/runs.py Switches to SimpleNamespace args type.
polylogue/cli/render.py Removes argparse dependency; adds prefs handling, redaction plumbing, centralized failure logging + summary rendering.
polylogue/cli/registry.py Deletes legacy command registry (argparse compatibility layer).
polylogue/cli/prune_cli.py New prune implementation for legacy outputs with rollback snapshot support.
polylogue/cli/prefs.py Switches to SimpleNamespace args type.
polylogue/cli/path_policy.py Extracts/renames path resolution helpers from legacy argparse helpers.
polylogue/cli/open_helper.py Switches to SimpleNamespace args type.
polylogue/cli/maintain.py Switches to SimpleNamespace and routes prune to new prune_cli.
polylogue/cli/init.py Switches to SimpleNamespace args type.
polylogue/cli/index_cli.py Switches to SimpleNamespace args type.
polylogue/cli/inbox.py Switches to SimpleNamespace args type.
polylogue/cli/imports.py Switches to SimpleNamespace, adds sanitize prefs/plumbing, uses centralized failure logging.
polylogue/cli/failure_logging.py New centralized failure logging (jsonl) and exit-reason classification.
polylogue/cli/examples.py Updates module docstring to remove argparse mention.
polylogue/cli/env_cli.py Switches to SimpleNamespace args type.
polylogue/cli/doctor.py Switches to SimpleNamespace args type.
polylogue/cli/context.py Replaces argparse namespaces with SimpleNamespace, updates DEFAULT_OUTPUT_ROOTS to include labeled roots.
polylogue/cli/config_editor.py Adds interactive config edit flow for updating config/settings.
polylogue/cli/config_cli.py New Click-era config show implementation (combined env+settings view).
polylogue/cli/completions_cli.py New Click-native completion script/engine entrypoints.
polylogue/cli/completion_engine.py Migrates completion engine from argparse parser introspection to Click command introspection.
polylogue/cli/compare_cli.py New provider-compare command implementation built on search results.
polylogue/cli/commands/sync.py Deletes legacy argparse sync command module.
polylogue/cli/commands/status.py Deletes legacy argparse status command module.
polylogue/cli/commands/search.py Deletes legacy argparse search command module.
polylogue/cli/commands/render.py Deletes legacy argparse render command module.
polylogue/cli/commands/README.md Deletes legacy argparse command-module documentation.
polylogue/cli/commands/maintain.py Deletes legacy argparse maintain command module.
polylogue/cli/commands/import_cmd.py Deletes legacy argparse import command module.
polylogue/cli/commands/config.py Deletes legacy argparse config command module.
polylogue/cli/commands/browse.py Deletes legacy argparse browse command module.
polylogue/cli/commands/attachments.py Deletes legacy argparse attachments command module.
polylogue/cli/commands/init.py Deletes legacy argparse commands package init.
polylogue/cli/click_options.py Adds OptionalValueChoiceOption to support --html (flag) or --html <mode>.
polylogue/cli/click_introspect.py Adds Click command-tree introspection helper for help/completions.
polylogue/cli/click_app.py Reworks Click entrypoint to dispatch directly to run_*_cli helpers; adds sanitize option; replaces argparse layer.
polylogue/cli/browse.py Routes browse subcommands to extracted CLI modules (branches/runs/status/inbox/stats).
polylogue/cli/branches_cli.py New extracted branches CLI implementation (diff/tree/html explorer/open).
polylogue/cli/attachments.py Switches to SimpleNamespace args type.
polylogue/cli/arg_helpers.py Deletes legacy argparse helper module (replaced by path_policy + Click).
polylogue/cli/main.py Adds python -m polylogue.cli entrypoint using Click main.
polylogue/cli/init.py Removes legacy argparse exports; keeps Click entrypoint exports.

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

Comment thread polylogue/local_sync.py
Comment on lines +236 to +246
if not force and not existing_dirty:
try:
from .importers.raw_storage import compute_hash
from .db import get_raw_import_by_conversation, open_connection

current_hash = compute_hash(session_path.read_bytes())
with open_connection(registrar.database.resolve_path()) as conn:
raw_row = get_raw_import_by_conversation(conn, provider, conversation_id)
if raw_row and raw_row["hash"] == current_hash:
entry["skipped"] = True
return entry

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.

Hash-based fast-path can skip re-import even when the requested processing options change (e.g., --sanitize-html / attachment_ocr). If a user re-runs local sync with sanitize enabled after previously writing unredacted outputs, this block will return skipped based solely on raw bytes, leaving unsanitized Markdown/HTML on disk. Consider incorporating the relevant option values into the skip key (store them in state and compare), or bypass this hash-skip when sanitize_html/attachment_ocr differs from what was used to produce the current output (can be read from existing document metadata like polylogue.redacted).

Copilot uses AI. Check for mistakes.
Comment thread polylogue/local_sync.py
Comment on lines +527 to +544
bundle_hash = None
bundle_provider = f"{provider}-export"
export_id = str(export_path)
if not force and not prune:
try:
from .importers.raw_storage import compute_hash

target = export_path
if export_path.is_dir():
conv_file = export_path / "conversations.json"
if conv_file.exists() and conv_file.is_file():
target = conv_file
bundle_hash = compute_hash(target.read_bytes())
state = registrar.get_state(bundle_provider, export_id)
if isinstance(state, dict) and state.get("bundleHash") == bundle_hash:
skipped_exports += 1
tracker.advance()
continue

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.

Export-bundle hash skip is keyed only on bundle bytes. If an operator changes flags that affect persisted output (notably --sanitize-html, and potentially attachment_ocr), the bundle can be skipped and stale/unredacted outputs retained. The skip state should include the option set (or a derived key), or the code should invalidate the skip when the desired processing flags differ from the last recorded run.

Copilot uses AI. Check for mistakes.
Comment on lines +76 to +82
with ZipFile(snapshot_path, "w") as zipf:
for _, path in all_legacy:
try:
if path.is_file():
zipf.write(path, arcname=path.name)
except Exception:
continue

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 rollback snapshot currently only archives legacy paths that are files. Any legacy *_attachments directories will be deleted but not included in the ZIP, so restore is incomplete. Also, using arcname=path.name can collide when pruning multiple roots (same filename overwrites in ZIP). Consider zipping directories recursively and storing a root-relative arcname to avoid collisions.

Copilot uses AI. Check for mistakes.
"claude_code": str(defaults.output_dirs.sync_claude_code),
"chatgpt": str(defaults.output_dirs.import_chatgpt),
"claude": str(defaults.output_dirs.import_claude),
"roots": {label: vars(paths) for label, paths in roots_map.items()},

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 --json mode, outputs.roots is built with vars(paths) where values are pathlib.Path objects. json.dumps(payload) will raise TypeError: Object of type PosixPath is not JSON serializable when labeled roots are configured. Convert the OutputDirs values to strings (or pass default=str) before dumping.

Suggested change
"roots": {label: vars(paths) for label, paths in roots_map.items()},
"roots": {
label: {
name: str(value) if value is not None else None
for name, value in vars(paths).items()
}
for label, paths in roots_map.items()
},

Copilot uses AI. Check for mistakes.

@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: c11c42893d

ℹ️ 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/local_sync.py Resolved
@Sinity

Sinity commented Apr 8, 2026

Copy link
Copy Markdown
Owner Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Apr 8, 2026

Copy link
Copy Markdown
✅ Actions performed

Full review triggered.

1 similar comment
@coderabbitai

coderabbitai Bot commented Apr 8, 2026

Copy link
Copy Markdown
✅ Actions performed

Full review triggered.

@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/click-consolidation-and-redaction branch April 9, 2026 23:02
Sinity added a commit that referenced this pull request Apr 22, 2026
…#38)

Delete the 1786-line monolithic `app.py`, the entire `cli/commands/`
argparse wrapper directory, `arg_helpers.py`, and `registry.py`. Click
becomes the sole CLI surface, with command handlers extracted into
focused modules and all `argparse.Namespace` usage replaced by
`types.SimpleNamespace`.

CLI architecture (deletions):
- `cli/app.py`: entire argparse entrypoint, parser builder, all
  `_dispatch_*` handlers, `build_parser()`, `CommandRegistry` usage
- `cli/commands/{sync,render,config,search,status,browse,maintain,
  attachments,import_cmd}.py`: argparse `setup_parser`/`dispatch` pairs
- `cli/arg_helpers.py`: argparse parent parsers, `PathPolicy`,
  `add_*_option` helpers
- `cli/registry.py`: `CommandRegistry` class and handler map
- `docs/architecture.md`: outdated architectural overview

CLI architecture (extractions from app.py into focused modules):
- `branches_cli.py`: branch exploration (was `run_inspect_branches`)
- `search_cli.py`: search, picker, preview (was `run_inspect_search`)
- `compare_cli.py`: provider comparison (was `run_compare_cli`)
- `completions_cli.py`: shell completion scripts and `_complete`
- `config_cli.py`: `config show` handler
- `config_editor.py`: new interactive `config edit` subcommand
- `prune_cli.py`: legacy file pruning (was `run_prune_cli`)
- `failure_logging.py`: `record_failure` (was `_record_failure`)
- `click_introspect.py`: `click_command_entries` for help/completions
- `click_options.py`: `OptionalValueChoiceOption` so `--html` works
  bare or with a value (`--html` → "on", `--html off` → "off")
- `path_policy.py`: `PathPolicy` + `resolve_path` from arg_helpers

Click entrypoint (`click_app.py`):
- `_should_use_plain()` moved here from app.py, now accepts keyword
  args instead of an argparse Namespace
- All command functions call `run_*_cli` directly with SimpleNamespace
  instead of routing through `*_cmd.dispatch()`
- `main()` wraps `cli.main(standalone_mode=False)` with explicit
  ClickException/Abort handling
- Completion engine rewired to walk Click's command tree instead of
  argparse subparsers

HTML redaction (`--sanitize-html`):
- New `polylogue/redaction.py` with `sanitize_text()` masking emails,
  OpenAI/Anthropic/GitHub/Slack/AWS/Google keys, and Bearer tokens
- Flag threaded through sync, import, render → `process_conversation`
  → `persist_document`, which applies redaction before computing the
  content hash and stamps `polylogue.redacted: true` in metadata
- Run payloads include `redacted: true` when the flag is active

Content-hash skip in `local_sync.py`:
- `_sync_sessions` compares the raw import hash from `raw_storage`
  against the stored hash before re-processing; skips when identical
- `_sync_export_bundles` tracks a per-bundle hash in state; unchanged
  archives skip the entire import call and increment `skipped`
- Existing mtime-based freshness check remains as a fallback

Context and summaries:
- `DEFAULT_OUTPUT_ROOTS` now collects paths from labeled roots as well
  as the base output dirs, so `prune` and `stats` cover all roots
- `summaries.py` gains `summarize_render()` with a Rich table for
  per-file token/attachment breakdown
- `resolve_html_settings` and related context functions accept plain
  objects instead of requiring argparse Namespace

Tests:
- All CLI tests migrated from argparse parser assertions to Click
  `CliRunner.invoke()` against the Click group
- New `test_redaction.py` covers email/key masking and the
  `persist_document(sanitize=True)` metadata stamp
- `test_local_sync.py` extended with content-hash skip assertions
  for both sessions and export bundles
@Sinity

Sinity commented Sep 30, 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: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.

3 participants