Repository navigation
Conversation
🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
- add consolidated plan and implementation checklist files\n- update AGENTS guidance, README, and supporting docs\n- keep hooks readme in sync with workflow notes\n\n🤖 Generated with [Claude Code](https://claude.com/claude-code)\n\nCo-Authored-By: Claude <[email protected]>
- centralize version resolution and stamp schema/polylogue versions into outputs\n- restore html auto defaults, improve status filtering, and tighten prompt/watch guardrails\n- extend CLI surface (attachments, prefs, open helper) with richer tests and HTML/search updates\n- refresh deps and implementation plumbing across sync/import/render paths\n\n🤖 Generated with [Claude Code](https://claude.com/claude-code)\n\nCo-Authored-By: Claude <[email protected]>
- restore top-level status command registration and parser wiring\n- adjust tests to expect status alias instead of argparse errors\n\n🤖 Generated with [Claude Code](https://claude.com/claude-code)\n\nCo-Authored-By: Claude <[email protected]>
- introduce message/tool collapse controls with CLI flags and propagation through render/import/sync pipelines\n- apply per-type folding in markdown generation and persist thresholds in metadata\n- keep watch/import/local sync flows aligned and update tests accordingly\n\n🤖 Generated with [Claude Code](https://claude.com/claude-code)\n\nCo-Authored-By: Claude <[email protected]>
- add schemaVersion/polylogueVersion to render/status/search JSON payloads\n- import schema constants where needed to avoid NameErrors\n\n🤖 Generated with [Claude Code](https://claude.com/claude-code)\n\nCo-Authored-By: Claude <[email protected]>
- add top-level env command with JSON/plain outputs and environment validations\n- include schema/version in payloads and keep consolidated command tests in sync\n\n🤖 Generated with [Claude Code](https://claude.com/claude-code)\n\nCo-Authored-By: Claude <[email protected]>
- include snake_case counterparts for search hit fields to reduce casing drift while keeping existing camelCase keys\n\n🤖 Generated with [Claude Code](https://claude.com/claude-code)\n\nCo-Authored-By: Claude <[email protected]>
- honor .polylogueignore patterns when syncing local sessions/exports\n- log skipped paths and add coverage for codex session filtering\n\n🤖 Generated with [Claude Code](https://claude.com/claude-code)\n\nCo-Authored-By: Claude <[email protected]>
- track ignored count in local sync result and log skipped paths\n- apply .polylogueignore filtering to session/export discovery with tests\n\n🤖 Generated with [Claude Code](https://claude.com/claude-code)\n\nCo-Authored-By: Claude <[email protected]>
- include snake_case + camelCase keys for status JSON payloads to smooth casing drift\n\n🤖 Generated with [Claude Code](https://claude.com/claude-code)\n\nCo-Authored-By: Claude <[email protected]>
Jump to message anchors when using --open and surface line hints for editors. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
Add an explicit Qdrant/index section heading so users know the wizard covers vector backend settings. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
Add a direnv-aware Python launcher for editors, wire VS Code to use it, and ignore developer .env files to avoid leaking secrets. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
Require existing base directories for watch mode unless the provider is explicitly allowed to create them, preventing accidental junk paths. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
Restore safe auto-creation for missing watch bases when running once or using default roots while still blocking accidental long-lived watchers on typos. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
Add a shared stamp_payload helper to emit snake+camel keys with version metadata and refactor search/status JSON outputs to use it. Includes coverage for casing and nested objects. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
Introduce "browse inbox" to list pending exports, optionally quarantine malformed items, and emit JSON summaries. Includes detection from inbox roots or an override directory plus test coverage for quarantine moves. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
| "runsDb": str(env.database.resolve_path()), | ||
| } | ||
| print(json.dumps(payload, indent=2)) | ||
| print(json.dumps(payload)) |
|
Warning Rate limit exceeded
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 7 minutes and 20 seconds. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the 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 configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (80)
📝 WalkthroughWalkthroughThis comprehensive pull request refactors core configuration and persistence systems while introducing new attachment-focused search and extraction features. Changes include: migrating configuration from core-driven defaults to XDG-based paths/UI/index config structure; upgrading database schema v2→v3 with attachments table and FTS indexing; adding attachment text extraction with optional OCR; expanding CLI with new subcommands (env, prefs, inbox, open, attachments, compare, maintain restore); rewriting NixOS module from per-target automation to fixed watch services; implementing non-TTY interaction guards and preflight disk checks; and updating documentation for expanded CLI surface. Changes
Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes Possibly related issues
Poem
✨ Finishing Touches🧪 Generate unit tests (beta)
|
…ttachment indexing (#28) Flatten the configuration model from nested defaults/drive/exports into a paths/ui/index structure, simplify provider directory naming, and replace the timer-based NixOS automation with long-running watch services. Add attachment text extraction with FTS indexing, introduce several new CLI commands, and harden every interactive prompt against non-TTY environments. Config schema (polylogue/config.py, core/configuration.py, config_validation.py): - Replace `defaults.output_dirs.*` with `paths.input_root`/`paths.output_root` and derive per-provider directories automatically - Rename provider directories: gemini-sync→gemini, gemini-render→render - Move UI knobs (collapse_threshold, html, theme) under `ui.*` - Add `persist_config()` to write config.json from init/settings CLI - Replace `POLYLOGUE_DRIVE_CREDENTIALS` with `POLYLOGUE_CREDENTIAL_PATH` and `POLYLOGUE_TOKEN_PATH` env vars; drop legacy `~/.polylogueconfig` - Default HTML to on, theme to dark NixOS module (nix/modules/polylogue.nix): - Delete the 230-line target/timer generator that read automation_targets.json - Replace with `mkWatchService` creating long-running systemd services per provider with `--watch` flags - Simplify options to `paths.{inputRoot,outputRoot}`, `ui.*`, `watch.*` - Add sinnix-profile wrapper module at modules/services/polylogue.nix Attachment indexing (services/attachment_text.py, db.py, search.py, conversation.py): - Extract text from PDF (pypdf), plaintext, HTML, and images (optional OCR via pillow+pytesseract) with configurable size limits - Add `attachments` table and `attachments_fts` virtual table (schema v3) - Wire `--in-attachments` and `--attachment-name` into search with a dedicated `_search_attachments()` path - Record per-attachment metadata (hash, mime, text bytes, OCR flag) via `ConversationRegistrar.record_attachments()` New CLI commands and flags (cli/app.py + new modules): - `compare` runs the same query across two providers side-by-side - `attachments stats|extract` for attachment inventory and bulk copy - `prefs list|set|clear` persists per-command flag defaults - `browse inbox` lists pending exports with provider auto-detection and quarantine for malformed items - `maintain restore` copies a snapshot directory back into the archive - `open` prints or opens the output path from the latest run - `env` validates XDG paths, credentials, index backend, and output roots - Global `--plain`/`--interactive`, `--max-disk`, `--profile-sql`, `--profile-io`, `--root`, `--offline`, `--snapshot`, `--stall-seconds` HTML template (html.py): - Sticky header with client-side text filter (press / to focus) - Two-column layout: TOC sidebar with attachment cards, content pane - Inject `id` anchors on headings for deep linking from `search --open` Rendering and persistence: - Per-type collapse thresholds (`--collapse-threshold-message`, `--collapse-threshold-tool`) via `resolve_collapse_thresholds()` - Anchor tags (`<a id="msg-N">`) injected per chunk for stable deep links - Content-hash skip in `persist_document()` avoids rewriting unchanged files - Branch map snippet prepended to canonical conversation.md - `--print-paths` flag on render/sync/import lists written files Safety and robustness: - `preflight_disk_requirement()` aborts when projected writes exceed `--max-disk` or available free space - Failure recording to `STATE_HOME/failures.jsonl` with classified exit reasons and actionable hints - Non-TTY prompts abort with SystemExit instead of blocking on stdin - Prune creates a rollback ZIP snapshot before deleting files - `.polylogueignore` file excludes sessions/exports from sync - Drive `--watch` rejected early; `--offline` blocks Drive sync Version and schema infrastructure (version.py, schema.py): - `_resolve_version()` reads from package metadata or pyproject.toml - `stamp_payload()` injects schemaVersion/polylogueVersion and dualizes keys to both snake_case and camelCase - Markdown frontmatter includes schema/version stamps Tests: - 15 new test files covering attachment search, inbox quarantine, ignore rules, env CLI, restore, schema utils, anchor line lookup, settings persistence, stats edge cases, and watch flag passthrough
There was a problem hiding this comment.
Pull request overview
Refactors Polylogue’s configuration and CLI surfaces to a new paths/ui/index schema, switches automation to long-running watch services, and adds first-class attachment text extraction + FTS indexing (with optional OCR) to make attachments searchable.
Changes:
- Reworked config loading/validation and persisted config writing (
config init/config set) around inbox/output roots and UI/index settings. - Added attachment extraction/indexing pipeline (SQLite schema v3 + attachment search mode + new attachments CLI).
- Expanded/reshaped CLI commands and non-TTY safety behavior (watch improvements, env/prefs/open/restore, richer status/stats outputs) with broad test additions.
Reviewed changes
Copilot reviewed 79 out of 80 changed files in this pull request and generated 8 comments.
Show a summary per file
| File | Description |
|---|---|
| tests/test_watch_cli.py | Extends watch tests (flags, debouncing, base-dir checks). |
| tests/test_ui.py | Adds non-TTY plain-mode prompt safety + dependency checks. |
| tests/test_status.py | Adds provider filter edge cases + custom drive path assertions. |
| tests/test_stats.py | Adds stats defaults, ignore-legacy, missing roots/dirs behavior. |
| tests/test_settings_cli.py | Ensures config set persists config.json roots/ui settings. |
| tests/test_search_open.py | Tests anchor-line lookup helper for search --open. |
| tests/test_schema_utils.py | Tests schema stamping + dual snake/camel key emission. |
| tests/test_render_utils_plain.py | Ensures plain non-TTY won’t auto-select multiple inputs. |
| tests/test_maintain_restore.py | Covers maintain restore copy flow. |
| tests/test_local_sync.py | Adds invalid export session path rejection tests. |
| tests/test_inbox_cli.py | Covers inbox listing + quarantine behavior. |
| tests/test_ignore_rules.py | Tests .polylogueignore exclusion during sync. |
| tests/test_idempotency.py | Updates schema expectations for new messages column(s). |
| tests/test_html.py | Adds empty-branch HTML rendering test. |
| tests/test_env_cli.py | Covers new env command + main() dispatch path. |
| tests/test_drive_client.py | Updates Drive env var behavior + non-TTY auth flow expectations. |
| tests/test_consolidated_commands.py | Updates parser expectations for status/env aliases + config show JSON shape. |
| tests/test_config_validation.py | Updates config validation tests for new ui.theme path. |
| tests/test_cli_help_env.py | Adds help --examples test + config/env JSON shape assertions. |
| tests/test_cli_flags.py | Adds flag parsing/dispatch tests (plain selection, collapse=0, drive watch rejection). |
| tests/test_cli_common.py | Covers non-TTY selection helpers + missing modifiedTime warning. |
| tests/test_attachment_search.py | End-to-end test that attachment text is indexed and searchable. |
| README.md | Documents new schema, inbox workflow, attachment search/OCR, new commands/flags. |
| pyproject.toml | Adds pypdf dependency and [ocr] extras. |
| polylogue/version.py | Adds version resolution helper + schema version constant. |
| polylogue/util.py | Adds disk preflight helper + run metadata flags. |
| polylogue/ui/facade.py | Tightens interactive dependency checks (gum/sk/bat/glow/delta). |
| polylogue/ui/init.py | Hardens plain prompts against non-TTY; adjusts default selection behavior. |
| polylogue/services/conversation_registrar.py | Records attachment names on messages + adds attachment recording API. |
| polylogue/services/attachment_text.py | New attachment text extraction (text/html/pdf + optional OCR). |
| polylogue/search.py | Adds attachment search mode and attachment-name filtering. |
| polylogue/schema.py | Adds shared payload stamping + dual snake/camel key emission. |
| polylogue/render.py | Adds schema/version stamps + anchors + per-type collapse thresholds. |
| polylogue/pipeline.py | Threads collapse-threshold overrides through document build pipeline. |
| polylogue/options.py | Extends option models for attachment search, OCR, per-type thresholds. |
| polylogue/local_sync.py | Introduces inbox provider detection, ignore rules, session validation, OCR plumbing. |
| polylogue/importers/codex.py | Threads collapse-threshold overrides + OCR flag through importer. |
| polylogue/importers/claude_code.py | Threads collapse-threshold overrides + OCR flag through importer. |
| polylogue/importers/claude_ai.py | Threads collapse-threshold overrides + OCR flag; standardizes thresholds. |
| polylogue/importers/chatgpt.py | Threads collapse-threshold overrides + OCR flag; standardizes thresholds. |
| polylogue/html.py | Refreshes HTML template (header/filter/TOC/attachments) + heading anchors. |
| polylogue/drive.py | Adds non-TTY auth guard + token path parameter support. |
| polylogue/drive_client.py | Switches to new credential/token env var names + passes token path explicitly. |
| polylogue/document_store.py | Adds schema/version stamps; improves idempotent “up-to-date” skip path. |
| polylogue/doctor.py | Surfaces credential/token/env override info in doctor report. |
| polylogue/db.py | Bumps DB schema to v3; adds attachments tables + FTS; adds message attachment_names. |
| polylogue/core/configuration.py | Implements new config schema loading (paths/ui/index) and removes legacy locations. |
| polylogue/core/config_validation.py | Updates pydantic model to validate new schema (paths/ui). |
| polylogue/conversation.py | Extracts/indexes attachment text at import time; records attachment rows. |
| polylogue/config.py | Adds persisted config writer + new DriveConfig defaults + new roots model surface. |
| polylogue/commands.py | Adds env.config to CommandEnv; extends status to include credential/token metadata; drive prefetching. |
| polylogue/cli/watch.py | Refactors watch to support more flags, debounce logging, stall warnings, snapshots. |
| polylogue/cli/sync.py | Applies sync prefs; adds offline/max-disk handling; prefetches drive chats. |
| polylogue/cli/status.py | Enhances status + stats JSON/CSV/NDJSON output; provider filtering behavior changes. |
| polylogue/cli/settings_cli.py | Persists config roots/UI defaults alongside settings changes. |
| polylogue/cli/render.py | Applies render prefs; adds max-disk preflight; prints written paths. |
| polylogue/cli/prefs.py | New prefs persistence CLI (list/set/clear). |
| polylogue/cli/open_helper.py | New open helper to print/open last output path. |
| polylogue/cli/maintain.py | Adds maintain restore (copy snapshot → dest) + disk preflight. |
| polylogue/cli/init.py | Updates init flow to write config.json with roots + index settings. |
| polylogue/cli/inbox.py | New inbox listing/quarantine command. |
| polylogue/cli/imports.py | Applies import prefs; adds OCR + collapse-threshold overrides + print-paths. |
| polylogue/cli/env_cli.py | New env validation command (XDG dirs, auth files, index backend). |
| polylogue/cli/doctor.py | Exposes credential/token paths + env overrides in doctor output. |
| polylogue/cli/context.py | Adds per-type collapse thresholds and allows collapse=0. |
| polylogue/cli/browse.py | Routes new browse inbox; adjusts stats subcommand error handling. |
| polylogue/cli/attachments.py | New attachments stats/extract CLI (filesystem scan or DB index). |
| polylogue/cli/arg_helpers.py | Adds --collapse-threshold-message/tool flags. |
| polylogue/cli/init.py | Exports new CLI helpers (_should_use_plain, attachments). |
| polylogue/cli_common.py | Hardens selection helpers for non-TTY and adds warnings on bad metadata. |
| polylogue/branch_explorer.py | Handles empty branch HTML + renders divergence snippets. |
| nix/python-deps.nix | Adds pypdf to Nix Python deps. |
| modules/services/polylogue.nix | Adds sinnix-profile wrapper module for watch services. |
| docs/providers/claude-ai.md | Updates provider docs for inbox-based export ingestion. |
| docs/providers/chatgpt.md | Updates provider docs for inbox-based export ingestion. |
| AGENTS.md | Updates workflow commands + documents new Drive env vars. |
| .vscode/settings.json | Adds workspace pytest + interpreter settings. |
| .gitignore | Ignores local .env files. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| # Text-like files | ||
| if suffix in TEXT_EXTENSIONS or (mime and mime.startswith("text/")): | ||
| text, truncated = _read_text_with_limits(path, max_bytes=max_bytes, max_chars=max_chars) | ||
| if suffix in {".html", ".htm"} or (mime and mime.startswith("text/html")): | ||
| text = _strip_html(text) | ||
| return AttachmentText(text=text, mime=mime, truncated=truncated, ocr_used=False, size_bytes=size) | ||
|
|
||
| # JSON and YAML can be normalised to reduce noise | ||
| if suffix in {".json", ".yaml", ".yml"}: | ||
| text, truncated = _read_text_with_limits(path, max_bytes=max_bytes, max_chars=max_chars) |
There was a problem hiding this comment.
extract_attachment_text()’s “JSON and YAML can be normalised” branch is currently unreachable because .json/.yaml/.yml are included in TEXT_EXTENSIONS, so the earlier “Text-like files” return executes first. As a result, JSON/YAML normalization never happens (and YAML would be attempted via json.loads anyway). Reorder the checks (handle JSON/YAML before the generic text case) and/or remove those suffixes from TEXT_EXTENSIONS, and consider using a YAML parser for YAML normalization if desired.
| def render_html(document: MarkdownDocument, options: HtmlRenderOptions) -> str: | ||
| theme = THEMES.get(options.theme, THEMES["light"]) | ||
| body_html = _MD_RENDERER.render(document.body) | ||
| # Inject anchors for headings to support deep links from search/open. | ||
| body_html = re.sub( | ||
| r"<h([1-6])>(.*?)</h\1>", | ||
| lambda m: f'<h{m.group(1)} id="{_anchorize(m.group(2))}">{m.group(2)}</h{m.group(1)}>', | ||
| body_html, | ||
| ) |
There was a problem hiding this comment.
Heading anchor injection is based on regex-substituting rendered HTML and passes m.group(2) (HTML, not plain text) into _anchorize(). If a heading contains inline markup (e.g., <code>, links), the generated id can include tag text or entities and may become unstable/invalid, breaking deep links from search --open. Consider deriving anchors from the Markdown source (or stripping tags/entities from the heading text before anchorizing), and ensure duplicate anchors are disambiguated.
| try: | ||
| stat = shutil.disk_usage(Path.cwd()) | ||
| free_bytes = stat.free | ||
| except Exception: |
There was a problem hiding this comment.
preflight_disk_requirement() checks free space using shutil.disk_usage(Path.cwd()), but the projected writes are to an output directory that may be on a different filesystem than the current working directory. This can lead to false passes/failures for --max-disk/free-space checks. Consider accepting a path (e.g., output root/target dir) and calling disk_usage() on that instead.
| if free_bytes is not None and projected_bytes > free_bytes: | ||
| msg = f"Projected disk use {projected_bytes / (1024 ** 3):.2f} GiB exceeds free space {free_bytes / (1024 ** 3):.2f} GiB" | ||
| if ui and hasattr(ui, "console"): | ||
| ui.console.print(f"[red]{msg}") | ||
| raise SystemExit(msg) |
There was a problem hiding this comment.
The Rich markup string printed on low free-space uses "[red]{msg}" without a closing tag. This can cause subsequent console output to inherit the color. Use a properly closed tag (e.g., "[red]{msg}[/red]") or avoid markup when printing errors.
| if dedup_key in seen: | ||
| continue | ||
| seen.add(dedup_key) | ||
|
|
||
| attachment_path = (conversation_dir / att.local_path).resolve() | ||
| if not attachment_path.exists(): | ||
| continue |
There was a problem hiding this comment.
Attachment indexing builds attachment_path via (conversation_dir / att.local_path).resolve(). If att.local_path is absolute (possible when attachment copying fails relative_to()), the join ignores conversation_dir, and the indexer may read/hash/index arbitrary files outside the conversation directory. For safety, reject absolute local_path values and enforce that the resolved path stays within conversation_dir before reading/indexing.
| try: | ||
| run_stats_cli(args, env) | ||
| except SystemExit: | ||
| return |
There was a problem hiding this comment.
browse stats swallows SystemExit from run_stats_cli() and returns, which makes polylogue browse stats ... exit with status 0 even on real errors (missing roots/dirs). This breaks scripting/CI that relies on non-zero exit codes. Prefer letting the SystemExit propagate (or re-raising it) so the CLI signals failure properly.
| try: | |
| run_stats_cli(args, env) | |
| except SystemExit: | |
| return | |
| run_stats_cli(args, env) |
| except Exception: | ||
| pass | ||
| # Minimal front matter parser. | ||
| warn(f"[yellow]frontmatter parse failed for {path}, falling back to minimal parser.") |
There was a problem hiding this comment.
warn() already applies [yellow] styling when printing, but _load_metadata() passes a message that includes [yellow]... markup. This results in nested/duplicated markup (and leaks markup into the collected warnings list for JSON output). Pass plain text to warn() and let the printer apply styling.
| warn(f"[yellow]frontmatter parse failed for {path}, falling back to minimal parser.") | |
| warn(f"frontmatter parse failed for {path}, falling back to minimal parser.") |
| a.text_content, | ||
| bm25(attachments_fts) AS score, | ||
| snippet(attachments_fts, '[', ']', ' … ', 4, 64) AS snippet | ||
| FROM attachments_fts | ||
| JOIN attachments AS a |
There was a problem hiding this comment.
In attachment search, snippet(attachments_fts, '[', ']', ' … ', 4, 64) uses column index 4, but per the attachments_fts schema the content column is index 5 (index 4 is attachment_name). This means snippets will be generated from the filename rather than the extracted attachment text. Use the content column index (or explicitly name the column via the appropriate snippet API) so previews reflect attachment body text.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8c8e5f5244
ℹ️ 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.
Actionable comments posted: 58
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (6)
polylogue/util.py (1)
420-441:⚠️ Potential issue | 🟠 Major
profile_ioandprofile_sqlare silently discarded.These fields are removed from
metadatahere, but the write path still never sends them torecord_run(). Every persisted run loses the profiling flags. Either add end-to-end storage for them or keep them inmetadatauntil the schema supports dedicated fields.Also applies to: 444-461
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@polylogue/util.py` around lines 420 - 441, The profile_io and profile_sql boolean flags are being stripped out of the metadata dict and never forwarded to record_run(), so persisted runs lose profiling info; update the code that builds metadata (the dict comprehension around metadata) to retain "profile_io" and "profile_sql" (or explicitly add them back into metadata after the comprehension) and then ensure the call to record_run() (and any surrounding persistence/write path) accepts and persists these fields by including metadata["profile_io"] and metadata["profile_sql"] (or adding them to the payload sent to record_run()) so profiling flags are stored end-to-end; adjust the metadata handling in the same function where metadata is constructed and where record_run() is invoked (references: metadata, profile_io, profile_sql, record_run).polylogue/branch_explorer.py (1)
639-661:⚠️ Potential issue | 🟡 MinorAvoid showing
divergence_snippettwice.
divergence_htmlalready includes the snippet for non-canonical branches with a divergence index, and canonical nodes can also carrydivergence_snippetfrom index0. The new unconditional block therefore duplicates the text on branched nodes and adds an unlabeled snippet to the canonical card.💡 Minimal fix
snippet_block = "" - if node.divergence_snippet: + if node.divergence_snippet and not node.is_canonical and not divergence_html: short = _short_snippet(node.divergence_snippet, limit=120) snippet_block = f'<div class="snippet">{html.escape(short)}</div>'🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@polylogue/branch_explorer.py` around lines 639 - 661, The snippet is rendered twice because divergence_html already embeds node.divergence_snippet for non-canonical nodes with a divergence_index, and the later snippet_block unconditionally renders the same text; update the snippet_block condition to only render when appropriate (e.g., only for canonical nodes) by changing the if that creates snippet_block to check node.is_canonical (or otherwise ensure node.divergence_index is not present) so that divergence_html and snippet_block don’t duplicate the same snippet; refer to divergence_html, snippet_block, node.divergence_snippet, node.is_canonical and node.divergence_index to locate and adjust the logic.polylogue/drive.py (1)
162-169: 🧹 Nitpick | 🔵 TrivialMove TTY check before printing the authorization URL.
The TTY check at line 168 happens after the authorization URL is already printed (line 167). In non-TTY contexts, users see the URL but then get an error. Consider moving the check earlier to fail fast:
♻️ Proposed fix
auth_url, _ = flow.authorization_url(prompt="consent", redirect_uri=flow.redirect_uri) + if not sys.stdin.isatty(): + raise RuntimeError( + f"Authorization requires an interactive terminal. " + f"Visit this URL manually: {auth_url}" + ) prompt = ( "Open this link in your browser to authorize Polylogue:\n" f" {auth_url}\n" ) print(colorize(prompt, "magenta") if verbose else prompt) - if not sys.stdin.isatty(): - raise RuntimeError("Authorization requires an interactive terminal; rerun with a TTY.")This also allows including the URL in the error message for manual follow-up.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@polylogue/drive.py` around lines 162 - 169, Move the interactive TTY guard to run before calling or printing the authorization URL so the function fails fast in non-interactive environments: check sys.stdin.isatty() immediately after obtaining auth_url (or even before calling flow.authorization_url) and raise the RuntimeError with a message that includes the auth_url for manual follow-up; update the block around flow.authorization_url, auth_url, colorize(..., "magenta") and verbose to only print the URL when the TTY check passes.tests/test_watch_cli.py (1)
23-25:⚠️ Potential issue | 🟡 MinorShared
DummyConsoleinstance may cause test pollution.
DummyUI.consoleis a class attribute assigned to a singleDummyConsole()instance. This means allDummyUIinstances share the same console, and captured lines from one test may leak into another.🔧 Proposed fix: make console an instance attribute
class DummyUI: plain = True - console = DummyConsole() + + def __init__(self): + self.console = DummyConsole() def summary(self, *_args, **_kwargs): pass🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@tests/test_watch_cli.py` around lines 23 - 25, DummyUI currently sets console as a shared class attribute (DummyUI.console = DummyConsole()), causing test pollution; change it to an instance attribute by adding an __init__ on DummyUI that assigns self.console = DummyConsole() (and preserve plain, e.g., self.plain = True) so each DummyUI instance gets its own DummyConsole and captured lines cannot leak between tests.polylogue/cli/imports.py (1)
139-151:⚠️ Potential issue | 🟠 MajorPropagate
print_pathsthrough the dispatcher.Each
argparse.Namespace(...)built here dropsprint_paths, so every downstreamgetattr(args, "print_paths", False)/ctx.get("print_paths")check seesFalsewhen the command goes throughrun_import_cli.polylogue import ... --print-pathstherefore produces no path output for any provider.Also applies to: 155-167, 171-182, 186-197
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@polylogue/cli/imports.py` around lines 139 - 151, The Namespace objects constructed in the import CLI (the argparse.Namespace assigned to ns) drop the print_paths attribute, so downstream code like run_import_cli and checks using getattr(args, "print_paths", False) or ctx.get("print_paths") always see False; update each Namespace construction (the ns variables in the import command branches) to include print_paths=args.print_paths (or args.print_paths if present) so the flag is propagated through the dispatcher to downstream import handlers.polylogue/ui/__init__.py (1)
85-97: 🧹 Nitpick | 🔵 TrivialUnreachable code on line 97.
The
return Noneat line 97 is unreachable because thewhile Trueloop only exits via explicitreturnstatements inside.♻️ Remove unreachable code
if 1 <= value <= len(options): return options[value - 1] self.console.print("[yellow]Enter a number corresponding to your choice.") - return None return self._facade.choose(prompt, options)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@polylogue/ui/__init__.py` around lines 85 - 97, The final "return None" after the infinite "while True" loop is unreachable; remove that trailing return to clean up the function containing the input loop (the block that reads response = input(f"{prompt} [1-{len(options)}]: ").strip(), checks response.isdigit(), and prints via self.console.print). Ensure only the existing in-loop return paths remain and delete the redundant return None at the end.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@modules/services/polylogue.nix`:
- Around line 9-10: The imports attribute is nested inside the wrapper's config
= mkIf block causing the upstream module
(inputs.polylogue.nixosModules.polylogue) to be imported too late; move the
imports = [ inputs.polylogue.nixosModules.polylogue ] out of the config = mkIf
... { } block to the top-level of the module (alongside options and config) so
the upstream module is imported before the wrapper references services.polylogue
or uses services.polylogue-sinnix.enable.
In `@nix/modules/polylogue.nix`:
- Around line 74-80: The gemini watch unit is starting the forbidden command
combination ("polylogue sync drive --watch") so enabling
services.polylogue.watch.gemini causes a crash loop; update the mkWatchService
invocation for the gemini entry (the line that uses lib.optional
cfg.watch.gemini and providerPaths.gemini) to use a supported command
combination or remove the --watch variant (e.g., call the correct watcher
subcommand the CLI accepts or omit the "sync drive --watch" arguments entirely),
ensuring the arguments match what polylogue/cli/app.py accepts so the service no
longer exits immediately.
- Around line 59-70: mkWatchService currently omits serviceConfig.User/Group so
watch units run as root; update mkWatchService (the
systemd.services."polylogue-watch-${name}" block) to set serviceConfig.User =
cfg.user and serviceConfig.Group = cfg.group (or derive Group from cfg.user if
cfg.group is not provided) but only add those attributes when cfg.user is
configured (use the existing pattern for optional attributes so you don't set
undefined values). Ensure you only change the serviceConfig block and keep
ExecStart/WorkingDirectory logic intact.
- Around line 34-38: The config directory is being created and registered
world-readable; update the activation script's directory creation and the
tmpfilesRules so the sensitive XDG config dir (cfg.configHome) is created with
restrictive permissions: change the install -d invocation that creates
cfg.configHome (currently using mode 0755) to use mode 0700, and update any
tmpfilesRules entries that set directories (including cfg.configHome and other
sensitive dirs) to 0755 to use 0700 instead so secrets like
cfg.index.qdrant.apiKey, credentials.json and token.json are only accessible to
the owner.
In `@polylogue/cli_common.py`:
- Around line 75-78: Remove the redundant inner "import sys" and rely on the
module-level import already present; locate the block that checks "if plain or
not sys.stdin.isatty():" (reference the variable plain and use of
sys.stdin.isatty()) and delete the duplicate import statement so only the
top-level sys import remains.
- Around line 157-172: The loop uses an unused index variable `idx` (for idx,
line in enumerate(lines)) in the selection UI; change the loop to iterate
directly over `lines` (for line in lines:) and remove the unused `idx` to
eliminate the unused variable warning while keeping the rest of the function
logic (header, ui.console.print, entries, prompt handling, and input/EOF
behavior) unchanged.
- Around line 149-156: Remove the duplicate local "import sys" inside the
plain-mode branch and rely on the module-level sys import; in the block starting
with "if getattr(ui, 'plain', False):" delete the inner import statement so the
code uses the already-imported sys for the isatty() check and retains the
existing ui.console.print and return behavior.
In `@polylogue/cli/app.py`:
- Around line 995-1004: The current anchor lookup uses a raw substring search so
an anchor like "msg-1" can match "msg-10"; update the logic so
_find_anchor_line(Path, anchor_label) performs an exact anchor match (e.g.,
match whole word or an HTML id attribute like id="msg-<n>" via a regex) instead
of substring containment before passing line_hint to open_in_editor; keep the
anchor_label construction (f"msg-{hit.position}") and ensure callers (the block
using hit.position, anchor_label, _find_anchor_line, and open_in_editor) rely on
the stricter match so --open --limit 1 jumps to the exact message.
- Around line 817-823: The parser currently requires the positional query which
breaks --from-stdin; change the positional "query" arg definition to be optional
(use nargs='?' / required=False) in the CLI parser where add_argument for
"query" is declared, update its help to mention --from-stdin and the "-"
placeholder, and keep the existing runtime logic in run_inspect_search()/the
block checking getattr(args, "from_stdin", False) to read stdin (or accept "-"
as a query) and validate that if not args.from_stdin and not args.query you
raise the same SystemExit(1) error; this ensures echo foo | polylogue search
--from-stdin works without a dummy positional.
- Around line 511-529: The snapshot currently writes each file using
arcname=path.name and skips directories, which flattens the hierarchy and drops
attachment dirs; change the ZipFile write logic (in the block that iterates over
all_legacy and uses path.is_file()) to preserve relative paths instead: when
path is a file, compute an arcname relative to a common base (e.g.,
path.relative_to(common_root) or by joining path.parts from the repo root) and
pass that as arcname so directory structure is preserved; when path is a
directory, walk it (os.walk or Path.rglob) and add each file with its relative
arcname so nested _attachments/ contents are included; keep the same
snapshot_path/ZipFile usage and only adjust how arcname and directory traversal
are handled.
In `@polylogue/cli/attachments.py`:
- Around line 71-160: The _run_attachment_stats function is too large and mixes
"indexed" vs "filesystem" logic; extract the indexed-path logic (currently using
_iter_indexed_attachments, ext filtering, totals/hashes/top_rows, json/csv
printing) into a helper like _attachment_stats_from_index(args, env) and move
the filesystem-specific logic into _attachment_stats_from_filesystem(args, env);
keep _run_attachment_stats responsible only for deciding use_index via
getattr(args, "from_index", False), calling the appropriate helper, and
forwarding ui.summary/prints, and ensure helpers return the same
payload/rows/lines structure (count/bytes/textBytes/ocrUsed/uniqueBytes/top or
CSV/JSON outputs) so behavior (json_lines/json/csv/limit/hash filters and ext
filtering) and early returns are preserved.
- Around line 15-38: The function _iter_indexed_attachments currently swallows
all exceptions from env.conversations.database.query and returns an empty list;
change the except block to catch Exception as e, log the error (e.g., via
env.logger.error(...) if env provides a logger, otherwise use the module
logging.error(...)) and include the exception details and context (query failure
in _iter_indexed_attachments / env.conversations.database.query) before
returning; ensure rows_raw is only iterated when the query succeeds and preserve
the empty-list fallback after logging.
- Around line 270-292: The loop in attachments.py counts copy failures (errors
variable) but neither logs the exception nor records which files failed; modify
the except block around shutil.copy2 in the loop to capture the exception and
the source file path (e.g., append file or str(file) to a new failed_paths
list), call the logger (or processLogger) to record a message including file and
exception details, increment errors as before, and ensure the function returns
or includes failed_paths in its output/summary along with copied and errors so
callers can see which files failed.
In `@polylogue/cli/browse.py`:
- Around line 24-27: The except block around run_stats_cli currently swallows
all SystemExit results; change it to catch SystemExit as e and only absorb
successful exits (e.code in (None, 0)) while re-raising non-zero exits so
failures propagate. Update the handler in browse.py (the try around
run_stats_cli(args, env)) to: except SystemExit as e: if e.code not in (None,
0): raise; return.
In `@polylogue/cli/env_cli.py`:
- Around line 53-63: The code risks AttributeError by accessing
env.config.index.qdrant_url and env.config.index.qdrant_collection without
ensuring env.config and env.config.index are present; update the logic around
backend and the qdrant checks to first retrieve and null-check the index config
(e.g., index_cfg = env.config.index if env.config and env.config.index else
None), use that to determine backend, and when backend == "qdrant" ensure
index_cfg is not None before accessing index_cfg.qdrant_url and
index_cfg.qdrant_collection—if index_cfg is missing, append EnvCheck entries
indicating missing qdrant config instead of directly accessing attributes.
- Around line 64-73: The code assumes env.config.defaults.output_dirs exists;
add a defensive null check before using it: verify env.config and
env.config.defaults and env.config.defaults.output_dirs (or use getattr with
defaults) and if missing set output_roots to a safe empty object or skip the
loop so _path_status isn't called with None; update the block that assigns
output_roots and the for loop that calls _path_status to handle the absent
output_dirs safely (referencing env.config.defaults.output_dirs, output_roots,
and _path_status).
In `@polylogue/cli/imports.py`:
- Around line 518-527: The UnboundLocalError occurs because chosen and cancelled
are used outside the interactive branch—move the block that calls
choose_single_entry(...) and the subsequent checks for cancelled and chosen back
inside the branch guarded by if session_id in {"pick", "?"} so chosen and
cancelled are only referenced after they are assigned; specifically locate the
choose_single_entry call (with format_line=_format_session and header "Select
Claude Code session") and the if cancelled / if chosen is None checks and indent
them under the interactive branch that handles session_id values "pick" and "?"
to ensure direct CLI calls (import claude-code <path>) don't reference
uninitialized variables.
In `@polylogue/cli/inbox.py`:
- Around line 114-123: The provider summary currently counts all entries in
entries and labels them "pending", causing quarantined items to be
double-reported; update the counting loop that builds summary (the block
referencing summary, entries, and prov) to only increment for entries whose
status == "pending" (i.e., check entry.get("status") == "pending") or
alternatively include status in the key (e.g., f"{prov}/{status}") so printed
totals reflect status; keep the quarantined lines using the existing quarantined
variable unchanged.
- Around line 51-55: The fallback roots still reference the removed
CONFIG.exports keys; update the logic that builds roots (the override_root
branch and the fallback appends) to use the new inbox/path configuration (e.g.,
replace CONFIG.exports.chatgpt and CONFIG.exports.claude with the new
CONFIG.inbox.chatgpt and CONFIG.inbox.claude or the correct inbox/path keys used
by the refactor), and also update any error messages that mention the old
exports keys (the related check around lines 110-111) to reference the new
inbox/path config names so the CLI no longer depends on obsolete CONFIG.exports
entries.
In `@polylogue/cli/init.py`:
- Around line 53-54: Remove unnecessary f-string prefixes for console.print
calls that contain no interpolation: replace f"..." with plain "..." in the
prompts rendered by init.py (e.g., the console.print calls currently using
f"[bold]Output Directory[/bold]" and f"Where should rendered conversations be
saved (root for all providers)?" as well as the similar prints around the other
occurrences noted at lines 66, 75, and 115). Ensure any string that does not
include placeholders is a normal string literal so only actual interpolated
strings keep the f-prefix.
- Around line 130-133: The int conversion currently catches all exceptions;
update the try/except around converting vector_raw to only catch ValueError so
unexpected errors aren't masked: replace the broad except in the block that sets
qdrant_vector from vector_raw (the try/except around int(vector_raw) and
assignment to qdrant_vector) with except ValueError and keep the fallback
assignment qdrant_vector = 1536.
In `@polylogue/cli/maintain.py`:
- Around line 42-45: The current broad except around the total_bytes calculation
swallows all exceptions; change it to catch OSError (or more specific
FileNotFoundError/PermissionError as appropriate) instead of Exception and emit
a warning so failures don't silently skip disk checks—target the block that
computes total_bytes from src.rglob("*") and log the failure (including
exception text) before falling back to a safe default or propagating; ensure
preflight_disk_requirement still receives a sensible value or aborts when the
estimation failed.
- Around line 28-31: Replace the unnecessary getattr calls on the argparse
namespace: use direct attribute access for src and dest (e.g., args.src,
args.dest) instead of getattr(args, "src")/getattr(args, "dest"), and set force
and json_mode via direct access (args.force, args.json) if those flags are
guaranteed by the parser; only keep getattr for force/json if those attributes
may be absent on args. Update the assignments for the variables src, dest,
force, and json_mode accordingly in the maintain.py block that currently
references args.
In `@polylogue/cli/prefs.py`:
- Around line 17-25: Don't silently swallow read/parse errors in _load_prefs:
only treat missing file as empty (catch FileNotFoundError and return {}), but
for JSON decode or IO errors re-raise or propagate the exception so callers know
the prefs are corrupt (reference _load_prefs and PREFS_PATH). When saving in
_save_prefs, write atomically by writing JSON to a temporary file in the same
directory, fsync the temp file and its directory, then atomically replace
PREFS_PATH with os.replace (or Path.replace) to avoid truncation/corruption on
failure; ensure the parent directory is created before creating the temp file.
In `@polylogue/cli/render.py`:
- Around line 51-52: The code currently checks render_prefs.get("--html") ==
"on" which only accepts the literal "on" and ignores other truthy strings;
change the assignment to use the helper _truthy to parse saved prefs (e.g.
html_enabled = _truthy(render_prefs.get("--html")) when args.html_mode ==
"auto") so values like "true", "yes", or "1" are handled correctly; update the
branch that references render_prefs, args.html_mode and html_enabled to call
_truthy(render_prefs.get("--html")) instead of comparing to "on".
In `@polylogue/cli/settings_cli.py`:
- Around line 58-92: config persistence is overwriting user paths even when only
theme/html/collapse settings changed; change the logic to detect path changes
separately (e.g. path_changed = bool(input_root or output_root or reset_flag))
and only compute/assign effective_input, effective_output, and rebuild
config_obj.defaults.output_dirs (using OutputDirs and the new_root) when
path_changed and/or output_root set; when only non-path settings changed, call
persist_config without changing input_root/output_root (e.g. pass None or omit
them depending on persist_config signature) so persist_config does not rewrite
existing paths; update references in this block: config_changed, path_changed,
effective_input, effective_output, persist_config,
config_obj.defaults.output_dirs, and OutputDirs.
In `@polylogue/cli/status.py`:
- Around line 56-67: The plain-text branch already respects --quiet via the
quiet/quiet_json flags, but the Rich output still unconditionally renders the
"Run Summary" and "Provider Summary" tables; update the Rich rendering logic to
check the same quiet flag logic (json_mode, json_verbose -> quiet_json, and
quiet) and skip emitting those summary tables when quiet or quiet_json is True
or when summary_only/dump_only indicate suppression; specifically, use the
existing variables (json_mode, quiet_json, quiet, dump_only, summary_only) to
gate the Rich rendering of the Run Summary and Provider Summary so that --quiet
suppresses those tables.
- Around line 512-527: When csv_destination == "-" the code writes CSV to stdout
using handle = sys.stdout but then continues and prints the human-readable
summary, corrupting the CSV stream; modify the block that handles
csv_destination (check csv_destination or handle) to return (or otherwise exit
the function) immediately after writer.writerows(display_rows) when writing to
stdout so no further console.print or text summary is emitted; update the csv
handling branch around the csv_destination/handle logic (the
writer/writerows(display_rows) section) to short-circuit only in the stdout
case.
In `@polylogue/cli/sync.py`:
- Around line 34-54: The _apply_sync_prefs function mutates the provided
argparse.Namespace (args) in place; change it to operate on a shallow copy and
return the modified copy (or explicitly document the in-place behavior).
Specifically, inside _apply_sync_prefs create a copy of args (e.g., via
copy.copy or Namespace(**vars(args))), use that copy when calling _apply_flag
and when setting html_mode, then return the copy instead of mutating the
original; alternatively, add a docstring to _apply_sync_prefs stating it mutates
args so callers know to pass a copy. Ensure you reference the same attributes
(html_mode, links_only, diff, prune, watch, once, attachment_ocr, offline) when
applying changes.
In `@polylogue/cli/watch.py`:
- Around line 54-62: The variable snapshot_dir is assigned but never used;
either remove snapshot_dir (and just use tmp_root for the snapshot
creation/print) or, if rollback is intended, keep snapshot_dir and add a clear
TODO comment and/or persist it to the function/state so it will be referenced
later. Update the block around args.snapshot, snapshot_dir, tmp_root, and the
exception handler accordingly so there are no unused variables remaining.
- Around line 54-62: The snapshot creation block currently catches a broad
Exception which can hide specific filesystem errors; change the except to catch
OSError (or a tuple like (OSError, shutil.Error) if you want copytree-specific
errors) and include the exception type in the ui.console.print message; update
the try/except around tempfile.mkdtemp and shutil.copytree where snapshot_dir,
tmp_root, args.snapshot, and ui.console.print are used so filesystem-related
failures are handled explicitly and the printed message shows both the exception
type and message.
In `@polylogue/commands.py`:
- Around line 789-803: status_command currently does two issues: the chained
getattr(env, "config", None).drive can raise AttributeError when config is None,
and setting limit = None when provider_filter is present can load an unbounded
number of runs; fix by making config access null-safe (e.g., config =
getattr(env, "config", None); drive_cfg = getattr(config, "drive", None) or
conditional check before using drive_cfg) so credentials_path/token_path access
is safe, and instead of setting limit = None when provider_filter is provided,
enforce a reasonable hard upper bound (introduce a constant like
MAX_PROVIDER_FILTER_RUNS or coerce limit = min(runs_limit or DEFAULT_MAX,
MAX_PROVIDER_FILTER_RUNS)) and emit a warning/log via the existing logger if the
requested limit exceeds the cap so callers know results are truncated; update
references in status_command (drive_cfg, credentials_path, token_path, limit,
provider_filter) accordingly.
In `@polylogue/conversation.py`:
- Around line 98-106: The _hash_file(Path) function currently swallows all
exceptions and returns None; modify it to log the exception before returning
None so file-system/hash failures are visible for debugging — e.g., obtain a
module logger (logging.getLogger(__name__)) and call logger.exception or
logger.error with the caught exception inside the except block in _hash_file,
preserving the current return None behavior.
- Around line 52-63: Remove the unused branch_dir parameter from the
_branch_map_snippet signature and from every call site that passes it (update
callers to call _branch_map_snippet(branch_ids) or pass only the branch_ids
list); inside _branch_map_snippet keep the existing logic that builds
branch_file and overlay_file using the branch_id variable, and update the type
hint to def _branch_map_snippet(branch_ids: List[str]) -> Optional[str]: so the
function signature and all references (calls to _branch_map_snippet and any type
annotations) are consistent.
In `@polylogue/core/config_validation.py`:
- Around line 69-75: Remove unnecessary quoted type annotations introduced by
from __future__ import annotations: unquote the return and parameter annotations
in the model_validator method ensure_theme (change "ConfigModel" to ConfigModel)
and likewise remove quotes around "IndexModel" at its declaration site; update
any other occurrences in this file so type hints use ConfigModel and IndexModel
directly (preserving existing imports) to avoid redundant string annotations.
In `@polylogue/doctor.py`:
- Around line 329-332: The environment variable values read into credential_env
and token_env are not applied, so credential_path and token_path should be set
to use the env overrides when present; change the assignment logic in doctor.py
so credential_path = credential_env or DEFAULT_CREDENTIALS and token_path =
token_env or DEFAULT_TOKEN (preserving existing names
DEFAULT_CREDENTIALS/DEFAULT_TOKEN), ensuring the subsequent file existence
checks that reference credential_path and token_path operate on the overridden
paths.
In `@polylogue/document_store.py`:
- Around line 333-345: The current early return when existing.content_hash ==
content_hash (with not force and not allow_dirty) skips necessary state and
artifact validation; instead, before returning a skipped
DocumentPersistenceResult, call conversation_is_current(),
registrar.record_document(), and update_index() to ensure the state DB is
up-to-date and artifacts (html, attachments_dir) exist or are recreated; keep
the same returned fields (markdown_path, html_path, attachments_dir, document,
slug, skipped=True, skip_reason="up-to-date", dirty=existing_dirty,
content_hash) but only after performing those validations and recreating missing
outputs (use expected_local_paths, html, attachments_dir to drive artifact
checks), so replace the direct return in the existing/content_hash check with
logic that runs the three validation/registration functions first and returns
only if they succeed.
In `@polylogue/drive_client.py`:
- Around line 24-25: DEFAULT_TOKEN is computed at import time from
_ENV_TOKEN_PATH which freezes the environment value; change DriveClient.__init__
to compute the token path at instance construction instead of relying on the
module-level DEFAULT_TOKEN: remove or stop using the module-scope
_ENV_TOKEN_PATH/DEFAULT_TOKEN and inside DriveClient.__init__ re-read
os.environ.get("POLYLOGUE_TOKEN_PATH"), fall back to CONFIG_DIR / "token.json"
(or Path(...).expanduser()) if the env var is not set, and update any use sites
to reference the instance-local token_path; apply the same fix for the analogous
module-scope DEFAULT_TOKEN usage in polylogue/config.py.
In `@polylogue/html.py`:
- Around line 16-22: The idx calculation in _human_size contains a redundant
conditional ("if num > 0 else 0") because the function already returns for num
<= 0; update the index computation in _human_size so it assumes num > 0 (e.g.,
compute idx = min(int(math.log(num, 1024)), len(units) - 1)) and remove the
unnecessary branch, keeping the rest of the function (units list, value
calculation and formatted return) unchanged.
- Around line 245-248: The regex in _anchorize uses a raw string with a double
backslash before the hyphen, which incorrectly matches a backslash+hyphen;
update the character class so the hyphen is treated literally (e.g., use
r"[^a-zA-Z0-9_-]+" or r"[^a-zA-Z0-9\-]+") in the re.sub call to correctly allow
hyphens in anchors and remove the erroneous backslash escape.
In `@polylogue/local_sync.py`:
- Around line 321-337: _detect_export_provider currently only checks for a
top-level "conversations.json" inside ZIPs; modify the ZIP branch to search
zf.namelist() for any member whose basename is "conversations.json"
(case-insensitive) or that endswith "/conversations.json", pick the first match,
open that member with zf.open(member_name) and json.load it, then pass the
parsed data to _classify_conversations_json; keep the try/except behavior and
ensure the selected member is read/decoded the same way as the existing code
when calling _classify_conversations_json.
In `@polylogue/render.py`:
- Around line 35-55: The isinstance(chunk, dict) guard inside
_collapse_threshold_for_chunk is redundant given chunk: Dict[str, Any]; remove
that conditional and directly compute role = str(chunk.get("role") or
"").lower() and tool_keys = ("toolResult", "toolResults", "toolCall",
"toolCalls", "functionCall", "arguments"), then use if role == "tool" or
any(chunk.get(key) for key in tool_keys): kind = "tool" before returning
overrides.get(kind, default) so the logic and symbol names (chunk, role,
tool_keys, kind, _collapse_threshold_for_chunk) remain the same but without the
unnecessary type check.
In `@polylogue/search.py`:
- Around line 73-75: The LIKE pattern uses raw user input (getattr(options,
"attachment_name")) so `%` and `_` in the input act as wildcards; escape `%`,
`_`, and the escape char itself before building the pattern and add an ESCAPE
clause to the SQL. Locate the block that appends "AND m.attachment_names LIKE ?"
and change it to use "AND m.attachment_names LIKE ? ESCAPE '\\'" (or
equivalent), compute escaped =
options.attachment_name.replace('\\','\\\\').replace('%','\\%').replace('_','\\_'),
then params.append(f"%{escaped}%"); apply the same escape logic to the other
occurrence referenced (lines ~201-203) to ensure consistent behavior.
In `@polylogue/services/attachment_text.py`:
- Around line 152-157: The YAML normalization currently uses json.loads which
will fail on YAML-only syntax; update the normalization logic that produces the
AttachmentText (the block that parses `text` and returns
`AttachmentText(text=text, mime=mime, ...)`) to use yaml.safe_load() for YAML
input (and then json.dumps(parsed, indent=2, ensure_ascii=False)) instead of
json.loads(), keeping json.loads() for JSON mime types if desired; add a safe
import of PyYAML (`yaml`) and catch exceptions from yaml.safe_load() so failures
fall back to returning the original text unchanged.
- Around line 101-116: In _extract_image_text, Image.open(path) is used without
closing the image; change it to open the image in a context manager (with
Image.open(path) as image:) so the underlying file handle is closed
automatically after calling pytesseract.image_to_string(image), keeping the
existing truncation logic and return values (text, truncated) unchanged; update
the block inside _extract_image_text accordingly, leaving the ImportError
handling intact.
- Around line 149-157: The JSON/YAML normalization block is unreachable because
suffixes like ".json", ".yaml", ".yml" are already matched by the earlier
TEXT_EXTENSIONS branch; update the logic in the function that builds
AttachmentText by moving the JSON/YAML handling (the block that calls
_read_text_with_limits, json.loads/json.dumps and returns AttachmentText) to
execute before the generic TEXT_EXTENSIONS/text-like branch, or alternatively
remove those extensions from TEXT_EXTENSIONS so the existing JSON/YAML-specific
code (and references to _read_text_with_limits and AttachmentText) will be hit;
ensure only one branch returns for a given suffix.
In `@polylogue/services/conversation_registrar.py`:
- Around line 198-200: The current assignment to attachment_names treats
record.links == [] the same as record.links == None; update the logic in the
block that sets attachment_names so it returns None when record.links is None,
an empty string when record.links is an empty list, and otherwise the sorted
comma-joined names; locate the code that computes attachment_names (uses
record.links and the set comprehension {name for name, _ in record.links}) and
change the conditional to explicitly check for None versus an empty iterable
before joining.
In `@polylogue/ui/facade.py`:
- Line 150: InteractiveConsoleFacade currently checks for
("gum","sk","bat","glow","delta") at init but only directly uses gum; change the
init-time check to only validate gum (i.e., limit the missing detection in
InteractiveConsoleFacade to "gum") and move or implement lazy/tool-specific
checks for "sk","bat","glow" in the fuzzy finder preview code in cli_common.py
and for "delta" in util.py (or add a shared lazy_check_tool helper that those
modules call at feature use time) so features can degrade gracefully and only
validate required tools when invoked.
In `@polylogue/util.py`:
- Around line 465-485: The free-space probe in preflight_disk_requirement
currently uses Path.cwd(); change it to accept a target path argument (e.g.,
target_path: Union[str, Path]) and compute the filesystem to probe by resolving
Path(target_path) and walking up to the nearest existing parent (or its parent
if the path itself exists) before calling shutil.disk_usage; keep the existing
fallback when disk_usage fails, and ensure all messages and comparisons
(threshold_bytes, free_bytes) use the discovered probe path instead of cwd so
render/restore checks the destination filesystem rather than the current working
directory.
In `@pyproject.toml`:
- Around line 39-42: The pyproject.toml [ocr] extra includes pytesseract which
depends on the system tesseract binary; update the README/installation docs to
add a short "OCR / Tesseract" section that states users who install the ocr
extra or enable the CLI flag --attachment-ocr must install the system Tesseract
engine, provide platform-specific install commands (e.g., apt/brew/choco) and a
note to verify tesseract is on PATH (and optionally how to check with `tesseract
--version`); reference the [ocr] extra and the --attachment-ocr flag so users
know when the dependency is required.
In `@README.md`:
- Line 23: The headings are attached directly to surrounding list content
causing markdownlint MD022; add a blank line both before and after the "## What
You Can Do" heading (and do the same for the other README heading that triggers
MD022) so each heading is separated from adjacent list or paragraph content,
preserving existing indentation and list markers.
In `@tests/test_cli_help_env.py`:
- Line 35: The test function test_help_examples_flag declares an unused capsys
fixture which triggers ARG001; remove the unused parameter from the function
signature (i.e., change def test_help_examples_flag(capsys): to def
test_help_examples_flag():) so the test no longer accepts the unused capsys
fixture.
In `@tests/test_env_cli.py`:
- Around line 33-37: Add an explicit assertion to test_env_cli_via_main to make
the intent clear: after calling _configure_isolated_state and invoking main()
(the CLI entrypoint), capture the CLI output (use pytest's capsys or monkeypatch
to capture stdout/stderr) or assert the process exit status/result, then assert
the expected string or non-empty output is present; update the test to reference
test_env_cli_via_main, _configure_isolated_state, and main when locating where
to capture and assert the CLI behavior.
In `@tests/test_ignore_rules.py`:
- Around line 46-49: The test builds slugs = {item.slug for item in
result.written} and then asserts the slug only startswith "keep"; replace that
imprecise check with an exact equality check: assert next(iter(slugs)) == "keep"
(or assert slugs == {"keep"}) so the test verifies the slug is exactly "keep"
using the existing result.written and slugs variables; leave result.skipped
assertion unchanged.
In `@tests/test_schema_utils.py`:
- Around line 6-16: Add a non-mutation assertion around the stamp_payload call:
capture a copy of the original payload (e.g., original = payload.copy() or deep
copy if nested) before calling stamp_payload and after getting stamped assert
that payload equals the original to ensure stamp_payload did not mutate its
input; reference the existing symbols payload, stamp_payload, and stamped when
adding the assertion.
In `@tests/test_stats.py`:
- Line 137: The test function test_run_stats_ignore_legacy declares an unused
monkeypatch fixture parameter; remove monkeypatch from the function signature so
it becomes def test_run_stats_ignore_legacy(tmp_path, capsys): and update any
references if present to keep the test signature consistent with actual fixtures
used.
In `@tests/test_status.py`:
- Around line 138-150: The test currently only asserts payload["recent_runs"] is
non-empty but doesn't ensure the runs are filtered by provider; update
test_status_provider_filter_respects_runs_limit so after calling
run_status_cli(args, env) you parse payload and assert that every item in
payload["recent_runs"] has provider == "drive" (or that set(item["provider"] for
item in payload["recent_runs"]) == {"drive"}), keeping the existing checks that
provider_summary only contains "drive" and using the same symbols: util.add_run,
CommandEnv, _status_args, run_status_cli, and payload.
In `@tests/test_watch_cli.py`:
- Line 142: Remove the unused pytest fixture parameters by editing the test
functions: drop the unused "monkeypatch" parameter from test_watch_passes_flags
and drop the unused "capsys" parameter from test_watch_logs_skipped_events
(these are the identifiers to locate the functions in tests/test_watch_cli.py).
Ensure the function signatures only include parameters that are actually
referenced in the test body so pytest won’t warn about unused fixtures.
---
Outside diff comments:
In `@polylogue/branch_explorer.py`:
- Around line 639-661: The snippet is rendered twice because divergence_html
already embeds node.divergence_snippet for non-canonical nodes with a
divergence_index, and the later snippet_block unconditionally renders the same
text; update the snippet_block condition to only render when appropriate (e.g.,
only for canonical nodes) by changing the if that creates snippet_block to check
node.is_canonical (or otherwise ensure node.divergence_index is not present) so
that divergence_html and snippet_block don’t duplicate the same snippet; refer
to divergence_html, snippet_block, node.divergence_snippet, node.is_canonical
and node.divergence_index to locate and adjust the logic.
In `@polylogue/cli/imports.py`:
- Around line 139-151: The Namespace objects constructed in the import CLI (the
argparse.Namespace assigned to ns) drop the print_paths attribute, so downstream
code like run_import_cli and checks using getattr(args, "print_paths", False) or
ctx.get("print_paths") always see False; update each Namespace construction (the
ns variables in the import command branches) to include
print_paths=args.print_paths (or args.print_paths if present) so the flag is
propagated through the dispatcher to downstream import handlers.
In `@polylogue/drive.py`:
- Around line 162-169: Move the interactive TTY guard to run before calling or
printing the authorization URL so the function fails fast in non-interactive
environments: check sys.stdin.isatty() immediately after obtaining auth_url (or
even before calling flow.authorization_url) and raise the RuntimeError with a
message that includes the auth_url for manual follow-up; update the block around
flow.authorization_url, auth_url, colorize(..., "magenta") and verbose to only
print the URL when the TTY check passes.
In `@polylogue/ui/__init__.py`:
- Around line 85-97: The final "return None" after the infinite "while True"
loop is unreachable; remove that trailing return to clean up the function
containing the input loop (the block that reads response = input(f"{prompt}
[1-{len(options)}]: ").strip(), checks response.isdigit(), and prints via
self.console.print). Ensure only the existing in-loop return paths remain and
delete the redundant return None at the end.
In `@polylogue/util.py`:
- Around line 420-441: The profile_io and profile_sql boolean flags are being
stripped out of the metadata dict and never forwarded to record_run(), so
persisted runs lose profiling info; update the code that builds metadata (the
dict comprehension around metadata) to retain "profile_io" and "profile_sql" (or
explicitly add them back into metadata after the comprehension) and then ensure
the call to record_run() (and any surrounding persistence/write path) accepts
and persists these fields by including metadata["profile_io"] and
metadata["profile_sql"] (or adding them to the payload sent to record_run()) so
profiling flags are stored end-to-end; adjust the metadata handling in the same
function where metadata is constructed and where record_run() is invoked
(references: metadata, profile_io, profile_sql, record_run).
In `@tests/test_watch_cli.py`:
- Around line 23-25: DummyUI currently sets console as a shared class attribute
(DummyUI.console = DummyConsole()), causing test pollution; change it to an
instance attribute by adding an __init__ on DummyUI that assigns self.console =
DummyConsole() (and preserve plain, e.g., self.plain = True) so each DummyUI
instance gets its own DummyConsole and captured lines cannot leak between tests.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: 3445141f-1196-467c-9373-a3710f624740
📒 Files selected for processing (80)
.gitignore.vscode/settings.jsonAGENTS.mdREADME.mddocs/providers/chatgpt.mddocs/providers/claude-ai.mdmodules/services/polylogue.nixnix/modules/polylogue.nixnix/python-deps.nixpolylogue/branch_explorer.pypolylogue/cli/__init__.pypolylogue/cli/app.pypolylogue/cli/arg_helpers.pypolylogue/cli/attachments.pypolylogue/cli/browse.pypolylogue/cli/context.pypolylogue/cli/doctor.pypolylogue/cli/env_cli.pypolylogue/cli/imports.pypolylogue/cli/inbox.pypolylogue/cli/init.pypolylogue/cli/maintain.pypolylogue/cli/open_helper.pypolylogue/cli/prefs.pypolylogue/cli/render.pypolylogue/cli/settings_cli.pypolylogue/cli/status.pypolylogue/cli/sync.pypolylogue/cli/watch.pypolylogue/cli_common.pypolylogue/commands.pypolylogue/config.pypolylogue/conversation.pypolylogue/core/config_validation.pypolylogue/core/configuration.pypolylogue/db.pypolylogue/doctor.pypolylogue/document_store.pypolylogue/drive.pypolylogue/drive_client.pypolylogue/html.pypolylogue/importers/chatgpt.pypolylogue/importers/claude_ai.pypolylogue/importers/claude_code.pypolylogue/importers/codex.pypolylogue/local_sync.pypolylogue/options.pypolylogue/pipeline.pypolylogue/render.pypolylogue/schema.pypolylogue/search.pypolylogue/services/attachment_text.pypolylogue/services/conversation_registrar.pypolylogue/ui/__init__.pypolylogue/ui/facade.pypolylogue/util.pypolylogue/version.pypyproject.tomltests/test_attachment_search.pytests/test_cli_common.pytests/test_cli_flags.pytests/test_cli_help_env.pytests/test_config_validation.pytests/test_consolidated_commands.pytests/test_drive_client.pytests/test_env_cli.pytests/test_html.pytests/test_idempotency.pytests/test_ignore_rules.pytests/test_inbox_cli.pytests/test_local_sync.pytests/test_maintain_restore.pytests/test_render_utils_plain.pytests/test_schema_utils.pytests/test_search_open.pytests/test_settings_cli.pytests/test_stats.pytests/test_status.pytests/test_ui.pytests/test_watch_cli.py
| config = mkIf config.services.polylogue-sinnix.enable { | ||
| imports = [ inputs.polylogue.nixosModules.polylogue ]; |
There was a problem hiding this comment.
🧩 Analysis chain
🌐 Web query:
In a NixOS module, is importsvalid insideconfig = { ... };, or must it be declared as a top-level module attribute?
💡 Result:
imports must be a top-level attribute of the module (alongside options and config). Putting imports inside config = { ... }; is not valid—config is for option values, while imports is part of the module “schema” that the module system reads before evaluating config. [1] [2] [3]
Correct:
{ ... }:
{
imports = [ ./other-module.nix ];
config = { ... };
}Incorrect:
{ ... }:
{
config = {
imports = [ ./other-module.nix ]; # not valid
};
}Sources: [1] [2] [3]
🏁 Script executed:
# Locate and inspect the polylogue.nix file
find . -name "polylogue.nix" -type fRepository: Sinity/polylogue
Length of output: 120
🏁 Script executed:
cat -n ./modules/services/polylogue.nixRepository: Sinity/polylogue
Length of output: 1321
Move the upstream module import to the top level.
imports is a top-level NixOS module attribute (alongside options and config). Nesting it inside config = mkIf ... { ... } prevents the upstream module from being imported before the wrapper's config block references services.polylogue, causing evaluation failure or undefined option errors.
🧩 Proposed fix
+ imports = [ inputs.polylogue.nixosModules.polylogue ];
+
- config = mkIf config.services.polylogue-sinnix.enable {
- imports = [ inputs.polylogue.nixosModules.polylogue ];
+ config = mkIf config.services.polylogue-sinnix.enable {📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| config = mkIf config.services.polylogue-sinnix.enable { | |
| imports = [ inputs.polylogue.nixosModules.polylogue ]; | |
| imports = [ inputs.polylogue.nixosModules.polylogue ]; | |
| config = mkIf config.services.polylogue-sinnix.enable { |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@modules/services/polylogue.nix` around lines 9 - 10, The imports attribute is
nested inside the wrapper's config = mkIf block causing the upstream module
(inputs.polylogue.nixosModules.polylogue) to be imported too late; move the
imports = [ inputs.polylogue.nixosModules.polylogue ] out of the config = mkIf
... { } block to the top-level of the module (alongside options and config) so
the upstream module is imported before the wrapper references services.polylogue
or uses services.polylogue-sinnix.enable.
| import sys | ||
|
|
||
| if plain or not sys.stdin.isatty(): | ||
| return None |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Duplicate import sys statement.
sys is already imported at the module level (line 5). This inner import is redundant.
♻️ Remove duplicate import
- import sys
-
if plain or not sys.stdin.isatty():
return None📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| import sys | |
| if plain or not sys.stdin.isatty(): | |
| return None | |
| if plain or not sys.stdin.isatty(): | |
| return None |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/cli_common.py` around lines 75 - 78, Remove the redundant inner
"import sys" and rely on the module-level import already present; locate the
block that checks "if plain or not sys.stdin.isatty():" (reference the variable
plain and use of sys.stdin.isatty()) and delete the duplicate import statement
so only the top-level sys import remains.
| if getattr(ui, "plain", False): | ||
| return entries[0], False | ||
| # Avoid blocking on stdin in non-interactive environments. | ||
| import sys | ||
|
|
||
| if not sys.stdin.isatty(): | ||
| if hasattr(ui, "console"): | ||
| ui.console.print("[yellow]Plain mode cannot prompt; pass --all/IDs or rerun with --interactive.") | ||
| return None, True |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Duplicate import sys statement inside function.
Same issue here - sys is already imported at module level.
♻️ Remove duplicate import
# Avoid blocking on stdin in non-interactive environments.
- import sys
-
if not sys.stdin.isatty():📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if getattr(ui, "plain", False): | |
| return entries[0], False | |
| # Avoid blocking on stdin in non-interactive environments. | |
| import sys | |
| if not sys.stdin.isatty(): | |
| if hasattr(ui, "console"): | |
| ui.console.print("[yellow]Plain mode cannot prompt; pass --all/IDs or rerun with --interactive.") | |
| return None, True | |
| if getattr(ui, "plain", False): | |
| # Avoid blocking on stdin in non-interactive environments. | |
| if not sys.stdin.isatty(): | |
| if hasattr(ui, "console"): | |
| ui.console.print("[yellow]Plain mode cannot prompt; pass --all/IDs or rerun with --interactive.") | |
| return None, True |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/cli_common.py` around lines 149 - 156, Remove the duplicate local
"import sys" inside the plain-mode branch and rely on the module-level sys
import; in the block starting with "if getattr(ui, 'plain', False):" delete the
inner import statement so the code uses the already-imported sys for the
isatty() check and retains the existing ui.console.print and return behavior.
| if header: | ||
| ui.console.print(header) | ||
| for idx, line in enumerate(lines): | ||
| ui.console.print(line) | ||
| while True: | ||
| try: | ||
| response = input((prompt or "select") + " [index or blank to cancel]: ").strip() | ||
| except EOFError: | ||
| return None, True | ||
| if not response: | ||
| return None, True | ||
| if response.isdigit(): | ||
| value = int(response) | ||
| if 0 <= value < len(entries): | ||
| return entries[value], False | ||
| ui.console.print("[yellow]Enter a valid numeric index or cancel with Enter.") |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Unused loop variable idx on line 159.
The static analysis correctly identifies that idx is not used within the loop body. Since the index is already embedded in the line string, you can simplify the loop.
♻️ Suggested fix
- for idx, line in enumerate(lines):
- ui.console.print(line)
+ for line in lines:
+ ui.console.print(line)📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if header: | |
| ui.console.print(header) | |
| for idx, line in enumerate(lines): | |
| ui.console.print(line) | |
| while True: | |
| try: | |
| response = input((prompt or "select") + " [index or blank to cancel]: ").strip() | |
| except EOFError: | |
| return None, True | |
| if not response: | |
| return None, True | |
| if response.isdigit(): | |
| value = int(response) | |
| if 0 <= value < len(entries): | |
| return entries[value], False | |
| ui.console.print("[yellow]Enter a valid numeric index or cancel with Enter.") | |
| if header: | |
| ui.console.print(header) | |
| for line in lines: | |
| ui.console.print(line) | |
| while True: | |
| try: | |
| response = input((prompt or "select") + " [index or blank to cancel]: ").strip() | |
| except EOFError: | |
| return None, True | |
| if not response: | |
| return None, True | |
| if response.isdigit(): | |
| value = int(response) | |
| if 0 <= value < len(entries): | |
| return entries[value], False | |
| ui.console.print("[yellow]Enter a valid numeric index or cancel with Enter.") |
🧰 Tools
🪛 Ruff (0.15.9)
[warning] 159-159: Loop control variable idx not used within loop body
(B007)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/cli_common.py` around lines 157 - 172, The loop uses an unused
index variable `idx` (for idx, line in enumerate(lines)) in the selection UI;
change the loop to iterate directly over `lines` (for line in lines:) and remove
the unused `idx` to eliminate the unused variable warning while keeping the rest
of the function logic (header, ui.console.print, entries, prompt handling, and
input/EOF behavior) unchanged.
| def _run_attachment_stats(args: argparse.Namespace, env: CommandEnv) -> None: | ||
| ui = env.ui | ||
| use_index = bool(getattr(args, "from_index", False)) | ||
| if use_index: | ||
| rows = _iter_indexed_attachments(env) | ||
| if not rows: | ||
| ui.console.print("[yellow]No indexed attachments found.") | ||
| return | ||
| ext_filter = getattr(args, "ext", None) | ||
| if ext_filter: | ||
| ext_lower = ext_filter.lower() | ||
| rows = [r for r in rows if str(r.get("attachment_name", "")).lower().endswith(ext_lower)] | ||
| total_bytes = sum(int(r.get("size_bytes") or 0) for r in rows) | ||
| total_text_bytes = sum(int(r.get("text_bytes") or 0) for r in rows) | ||
| ocr_used = sum(1 for r in rows if r.get("ocr_used")) | ||
| hashes: Dict[str, Tuple[int, str]] = {} | ||
| hashed_bytes = 0 | ||
| if getattr(args, "hash", False): | ||
| for r in rows: | ||
| digest = r.get("content_hash") | ||
| size_val = int(r.get("size_bytes") or 0) | ||
| if digest and digest not in hashes: | ||
| hashes[digest] = (size_val, r.get("attachment_path") or "") | ||
| hashed_bytes += size_val | ||
| limit = getattr(args, "limit", 10) | ||
| json_lines = bool(getattr(args, "json_lines", False)) | ||
| json_mode = bool(getattr(args, "json", False) or json_lines) | ||
| top_rows = sorted( | ||
| rows, | ||
| key=lambda r: (int(r.get("size_bytes") or 0), str(r.get("attachment_name") or "")), | ||
| reverse=True, | ||
| ) | ||
| if limit > 0: | ||
| top_rows = top_rows[:limit] | ||
| if json_lines: | ||
| for row in rows: | ||
| print(json.dumps(row, separators=(",", ":"))) | ||
| return | ||
| if json_mode: | ||
| payload = { | ||
| "count": len(rows), | ||
| "bytes": total_bytes, | ||
| "textBytes": total_text_bytes, | ||
| "ocrUsed": ocr_used, | ||
| "uniqueBytes": hashed_bytes if getattr(args, "hash", False) else None, | ||
| "top": top_rows, | ||
| } | ||
| print(json.dumps(payload, indent=2)) | ||
| return | ||
| csv_target = getattr(args, "csv", None) | ||
| if csv_target: | ||
| target = Path(csv_target) | ||
| fieldnames = [ | ||
| "attachment_name", | ||
| "size_bytes", | ||
| "text_bytes", | ||
| "ocr_used", | ||
| "attachment_path", | ||
| "provider", | ||
| "conversation_id", | ||
| "branch_id", | ||
| "message_id", | ||
| ] | ||
| if str(target) == "-": | ||
| writer = csv.DictWriter(env.ui.console.file, fieldnames=fieldnames) | ||
| writer.writeheader() | ||
| writer.writerows(top_rows) | ||
| else: | ||
| target = target.expanduser() | ||
| target.parent.mkdir(parents=True, exist_ok=True) | ||
| with target.open("w", newline="", encoding="utf-8") as handle: | ||
| writer = csv.DictWriter(handle, fieldnames=fieldnames) | ||
| writer.writeheader() | ||
| writer.writerows(top_rows) | ||
| ui.console.print(f"[green]Wrote attachment rows to {target}") | ||
| return | ||
| lines = [ | ||
| f"Indexed attachments: {len(rows)} (~{total_bytes / (1024 * 1024):.2f} MiB) text={total_text_bytes} bytes", | ||
| f"OCR used on {ocr_used} attachment(s)", | ||
| ] | ||
| if getattr(args, "hash", False): | ||
| lines.append(f"Unique (by hash): {len(hashes)} (~{hashed_bytes / (1024 * 1024):.2f} MiB)") | ||
| if top_rows: | ||
| lines.append("Top attachments:") | ||
| for row in top_rows: | ||
| lines.append( | ||
| f" {row.get('attachment_name')} {row.get('size_bytes')} bytes text={row.get('text_bytes')} ({row.get('attachment_path')})" | ||
| ) | ||
| ui.summary("Attachment Stats (index)", lines) | ||
| return |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Consider refactoring _run_attachment_stats for maintainability.
This function has 118 statements and 33 branches. While the logic is coherent, extracting the indexed and filesystem paths into separate helper functions would improve readability and testability.
🧰 Tools
🪛 Ruff (0.15.9)
[warning] 71-71: Too many return statements (8 > 6)
(PLR0911)
[warning] 71-71: Too many branches (33 > 12)
(PLR0912)
[warning] 71-71: Too many statements (118 > 50)
(PLR0915)
[warning] 156-158: Use list.extend to create a transformed list
(PERF401)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/cli/attachments.py` around lines 71 - 160, The
_run_attachment_stats function is too large and mixes "indexed" vs "filesystem"
logic; extract the indexed-path logic (currently using
_iter_indexed_attachments, ext filtering, totals/hashes/top_rows, json/csv
printing) into a helper like _attachment_stats_from_index(args, env) and move
the filesystem-specific logic into _attachment_stats_from_filesystem(args, env);
keep _run_attachment_stats responsible only for deciding use_index via
getattr(args, "from_index", False), calling the appropriate helper, and
forwarding ui.summary/prints, and ensure helpers return the same
payload/rows/lines structure (count/bytes/textBytes/ocrUsed/uniqueBytes/top or
CSV/JSON outputs) so behavior (json_lines/json/csv/limit/hash filters and ext
filtering) and early returns are preserved.
| slugs = {item.slug for item in result.written} | ||
| assert len(slugs) == 1 | ||
| assert next(iter(slugs)).startswith("keep") | ||
| assert result.skipped == 0 |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Consider a more precise assertion for the slug.
The assertion next(iter(slugs)).startswith("keep") is slightly imprecise since it only checks the prefix. Given the test setup, the slug should be exactly "keep".
🔧 More precise assertion
slugs = {item.slug for item in result.written}
- assert len(slugs) == 1
- assert next(iter(slugs)).startswith("keep")
+ assert slugs == {"keep"}
assert result.skipped == 0🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@tests/test_ignore_rules.py` around lines 46 - 49, The test builds slugs =
{item.slug for item in result.written} and then asserts the slug only startswith
"keep"; replace that imprecise check with an exact equality check: assert
next(iter(slugs)) == "keep" (or assert slugs == {"keep"}) so the test verifies
the slug is exactly "keep" using the existing result.written and slugs
variables; leave result.skipped assertion unchanged.
| stamped = stamp_payload(payload) | ||
|
|
||
| # versions injected | ||
| assert "schemaVersion" in stamped | ||
| assert "polylogueVersion" in stamped | ||
|
|
||
| # dual casing | ||
| assert stamped["foo_bar"] == 1 | ||
| assert stamped["fooBar"] == 1 | ||
| assert stamped["nested_val"]["inner_key"] == "x" | ||
| assert stamped["nestedVal"]["innerKey"] == "x" |
There was a problem hiding this comment.
Add a non-mutation assertion for payload before/after stamping.
This test validates output shape well, but it currently allows an in-place mutation regression to slip through.
✅ Suggested test hardening
def test_stamp_payload_dual_keys_and_versions():
- payload = {"foo_bar": 1, "nested_val": {"inner_key": "x"}}
+ payload = {"foo_bar": 1, "nested_val": {"inner_key": "x"}}
+ original = {"foo_bar": 1, "nested_val": {"inner_key": "x"}}
stamped = stamp_payload(payload)
@@
assert stamped["foo_bar"] == 1
assert stamped["fooBar"] == 1
assert stamped["nested_val"]["inner_key"] == "x"
assert stamped["nestedVal"]["innerKey"] == "x"
+
+ # input remains unchanged
+ assert payload == original
+ assert "fooBar" not in payload
+ assert "nestedVal" not in payload🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@tests/test_schema_utils.py` around lines 6 - 16, Add a non-mutation assertion
around the stamp_payload call: capture a copy of the original payload (e.g.,
original = payload.copy() or deep copy if nested) before calling stamp_payload
and after getting stamped assert that payload equals the original to ensure
stamp_payload did not mutate its input; reference the existing symbols payload,
stamp_payload, and stamped when adding the assertion.
| assert set(payload["directories"]) == {str(render_dir.parent), str(codex_dir.parent)} | ||
|
|
||
|
|
||
| def test_run_stats_ignore_legacy(monkeypatch, tmp_path, capsys): |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Remove unused monkeypatch fixture parameter.
The monkeypatch parameter is declared but not used in this test function. Remove it to keep the test signature clean.
♻️ Proposed fix
-def test_run_stats_ignore_legacy(monkeypatch, tmp_path, capsys):
+def test_run_stats_ignore_legacy(tmp_path, capsys):📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| def test_run_stats_ignore_legacy(monkeypatch, tmp_path, capsys): | |
| def test_run_stats_ignore_legacy(tmp_path, capsys): |
🧰 Tools
🪛 Ruff (0.15.9)
[warning] 137-137: Unused function argument: monkeypatch
(ARG001)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@tests/test_stats.py` at line 137, The test function
test_run_stats_ignore_legacy declares an unused monkeypatch fixture parameter;
remove monkeypatch from the function signature so it becomes def
test_run_stats_ignore_legacy(tmp_path, capsys): and update any references if
present to keep the test signature consistent with actual fixtures used.
| def test_status_provider_filter_respects_runs_limit(state_env, capsys): | ||
| # Add multiple providers; ensure provider filter still returns data when runs_limit is small. | ||
| util.add_run({"cmd": "sync drive", "provider": "drive", "count": 1, "timestamp": "2024-03-01T00:00:00Z"}) | ||
| util.add_run({"cmd": "render", "provider": "render", "count": 1, "timestamp": "2024-03-02T00:00:00Z"}) | ||
|
|
||
| env = CommandEnv(ui=DummyUI()) | ||
| args = _status_args(json=True, providers="drive", runs_limit=1) | ||
|
|
||
| run_status_cli(args, env) | ||
|
|
||
| payload = json.loads(capsys.readouterr().out) | ||
| assert list(payload["provider_summary"].keys()) == ["drive"] | ||
| assert payload["recent_runs"] |
There was a problem hiding this comment.
Validate the provider on recent_runs too.
assert payload["recent_runs"] only proves that something was returned. A regression where the summary is filtered to drive but the run list still contains the latest render entry would still pass.
🧰 Tools
🪛 Ruff (0.15.9)
[warning] 138-138: Unused function argument: state_env
(ARG001)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@tests/test_status.py` around lines 138 - 150, The test currently only asserts
payload["recent_runs"] is non-empty but doesn't ensure the runs are filtered by
provider; update test_status_provider_filter_respects_runs_limit so after
calling run_status_cli(args, env) you parse payload and assert that every item
in payload["recent_runs"] has provider == "drive" (or that set(item["provider"]
for item in payload["recent_runs"]) == {"drive"}), keeping the existing checks
that provider_summary only contains "drive" and using the same symbols:
util.add_run, CommandEnv, _status_args, run_status_cli, and payload.
| run_watch_cli(args, env) | ||
|
|
||
|
|
||
| def test_watch_passes_flags(monkeypatch, tmp_path): |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Remove unused test parameters.
monkeypatch in test_watch_passes_flags and capsys in test_watch_logs_skipped_events are declared but not used.
🔧 Proposed fix
-def test_watch_passes_flags(monkeypatch, tmp_path):
+def test_watch_passes_flags(tmp_path):-def test_watch_logs_skipped_events(monkeypatch, tmp_path, capsys):
+def test_watch_logs_skipped_events(monkeypatch, tmp_path):Also applies to: 162-162
🧰 Tools
🪛 Ruff (0.15.9)
[warning] 142-142: Unused function argument: monkeypatch
(ARG001)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@tests/test_watch_cli.py` at line 142, Remove the unused pytest fixture
parameters by editing the test functions: drop the unused "monkeypatch"
parameter from test_watch_passes_flags and drop the unused "capsys" parameter
from test_watch_logs_skipped_events (these are the identifiers to locate the
functions in tests/test_watch_cli.py). Ensure the function signatures only
include parameters that are actually referenced in the test body so pytest won’t
warn about unused fixtures.
|
@coderabbitai full review |
✅ Actions performedFull review triggered. |
…ttachment indexing (#28) Flatten the configuration model from nested defaults/drive/exports into a paths/ui/index structure, simplify provider directory naming, and replace the timer-based NixOS automation with long-running watch services. Add attachment text extraction with FTS indexing, introduce several new CLI commands, and harden every interactive prompt against non-TTY environments. Config schema (polylogue/config.py, core/configuration.py, config_validation.py): - Replace `defaults.output_dirs.*` with `paths.input_root`/`paths.output_root` and derive per-provider directories automatically - Rename provider directories: gemini-sync→gemini, gemini-render→render - Move UI knobs (collapse_threshold, html, theme) under `ui.*` - Add `persist_config()` to write config.json from init/settings CLI - Replace `POLYLOGUE_DRIVE_CREDENTIALS` with `POLYLOGUE_CREDENTIAL_PATH` and `POLYLOGUE_TOKEN_PATH` env vars; drop legacy `~/.polylogueconfig` - Default HTML to on, theme to dark NixOS module (nix/modules/polylogue.nix): - Delete the 230-line target/timer generator that read automation_targets.json - Replace with `mkWatchService` creating long-running systemd services per provider with `--watch` flags - Simplify options to `paths.{inputRoot,outputRoot}`, `ui.*`, `watch.*` - Add sinnix-profile wrapper module at modules/services/polylogue.nix Attachment indexing (services/attachment_text.py, db.py, search.py, conversation.py): - Extract text from PDF (pypdf), plaintext, HTML, and images (optional OCR via pillow+pytesseract) with configurable size limits - Add `attachments` table and `attachments_fts` virtual table (schema v3) - Wire `--in-attachments` and `--attachment-name` into search with a dedicated `_search_attachments()` path - Record per-attachment metadata (hash, mime, text bytes, OCR flag) via `ConversationRegistrar.record_attachments()` New CLI commands and flags (cli/app.py + new modules): - `compare` runs the same query across two providers side-by-side - `attachments stats|extract` for attachment inventory and bulk copy - `prefs list|set|clear` persists per-command flag defaults - `browse inbox` lists pending exports with provider auto-detection and quarantine for malformed items - `maintain restore` copies a snapshot directory back into the archive - `open` prints or opens the output path from the latest run - `env` validates XDG paths, credentials, index backend, and output roots - Global `--plain`/`--interactive`, `--max-disk`, `--profile-sql`, `--profile-io`, `--root`, `--offline`, `--snapshot`, `--stall-seconds` HTML template (html.py): - Sticky header with client-side text filter (press / to focus) - Two-column layout: TOC sidebar with attachment cards, content pane - Inject `id` anchors on headings for deep linking from `search --open` Rendering and persistence: - Per-type collapse thresholds (`--collapse-threshold-message`, `--collapse-threshold-tool`) via `resolve_collapse_thresholds()` - Anchor tags (`<a id="msg-N">`) injected per chunk for stable deep links - Content-hash skip in `persist_document()` avoids rewriting unchanged files - Branch map snippet prepended to canonical conversation.md - `--print-paths` flag on render/sync/import lists written files Safety and robustness: - `preflight_disk_requirement()` aborts when projected writes exceed `--max-disk` or available free space - Failure recording to `STATE_HOME/failures.jsonl` with classified exit reasons and actionable hints - Non-TTY prompts abort with SystemExit instead of blocking on stdin - Prune creates a rollback ZIP snapshot before deleting files - `.polylogueignore` file excludes sessions/exports from sync - Drive `--watch` rejected early; `--offline` blocks Drive sync Version and schema infrastructure (version.py, schema.py): - `_resolve_version()` reads from package metadata or pyproject.toml - `stamp_payload()` injects schemaVersion/polylogueVersion and dualizes keys to both snake_case and camelCase - Markdown frontmatter includes schema/version stamps Tests: - 15 new test files covering attachment search, inbox quarantine, ignore rules, env CLI, restore, schema utils, anchor line lookup, settings persistence, stats edge cases, and watch flag passthrough
|
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
Flatten the configuration model from nested
defaults/drive/exportssections into apaths/ui/indexschema, replace the NixOS timer-based automation with long-running watch services, add full-text attachment indexing with optional OCR, and introduce seven new CLI commands — all while hardening every interactive prompt against non-TTY environments.Motivation
The config schema carried unnecessary indirection: output directories were buried under
defaults.output_dirs.*, provider naming was inconsistent (gemini-syncvscodex), and exports lived in a confusingly separateexports.*section. The NixOS module reflected this complexity — a 230-line target/timer generator read anautomation_targets.jsonmanifest to produce oneshot services with timers, but every real deployment just ran--watchin a loop anyway. Meanwhile, attachment content was completely invisible to search despite being present on disk.I wanted to:
config initcan write it directlyConfig schema rewrite
The old schema:
{ "defaults": { "collapse_threshold": 25, "html_previews": false, "html_theme": "light", "output_dirs": { "render": "...", "sync_drive": "...", ... } }, "drive": { "credentials_path": "...", "token_path": "..." }, "exports": { "chatgpt": "...", "claude": "..." } }The new schema:
{ "paths": { "input_root": "~/.local/share/polylogue/inbox", "output_root": "~/.local/share/polylogue/archive" }, "ui": { "collapse_threshold": 25, "html": true, "theme": "dark" }, "index": { "backend": "sqlite", "qdrant": { ... } } }Per-provider directories derive from
output_rootautomatically —render,gemini,codex,claude-code,chatgpt,claude. The inbox replaces the oldexportssection: drop ZIPs anywhere underinput_rootand provider detection figures out the rest. Drive credentials usePOLYLOGUE_CREDENTIAL_PATH/POLYLOGUE_TOKEN_PATHenv vars instead of the oldPOLYLOGUE_DRIVE_CREDENTIALS.NixOS module rewrite
Before:
automation_targets.json→mkServiceForgenerating oneshot services + timers per target, with per-target option submodules forworkingDir,outputDir,extraArgs,timer.interval, etc.After:
mkWatchServicegenerating a simpleType=simpleservice per provider withRestart=always. Five boolean toggles (watch.gemini,watch.codex, etc.) replace the entire target machinery. A separatemodules/services/polylogue.nixprovides a sinnix-profile wrapper for personal deployments.Attachment text extraction and search
New
services/attachment_text.pyextracts text from:.txt,.md,.py,.json, etc.) — read with byte/char limitspypdf(added to dependencies)pillow+pytesseract(new[ocr]extra)The extracted text flows into a new
attachmentstable andattachments_ftsvirtual FTS5 table (schema v3). Search gains--in-attachmentsto query attachment content and--attachment-nameto filter by filename. Each attachment row records hash, MIME type, text byte count, and whether OCR was used.New CLI commands
compare QUERY --provider-a A --provider-b Battachments stats|extractprefs list|set|clearbrowse inboxmaintain restore --from SNAP --to DESTopen [--provider X]env [--json]HTML template refresh
The preview template gains a sticky header with a
/-focusable text filter, a two-column layout with a TOC sidebar and attachment cards, andidanchors on every heading for deep linking fromsearch --open.Safety hardening
--max-disk Naborts if projected writes exceed N GiB or available free spaceSTATE_HOME/failures.jsonlwith classified exit reasonsSystemExitinstead of blocking on stdinprunecreates a rollback ZIP before deleting.polylogueignoreexcludes sessions from sync--offlineblocks Drive operations;--watchrejected for Drive earlyTesting
15 new test files cover attachment search, inbox quarantine/detection, ignore rules, env CLI validation, restore flow, schema stamping, anchor-line lookup, settings persistence, stats edge cases (missing roots, ignore-legacy, CSV export), status provider filtering, watch flag passthrough, and non-TTY prompt behavior.