Repository navigation
Conversation
📝 WalkthroughWalkthroughThis PR refactors the Polylogue CLI from an interactive menu-driven system to an explicit subcommand architecture, removes configurable branch-export modes in favor of fixed layouts, eliminates the automation/systemd integration, adds shell completions and new dashboards/runs/env/index commands, vendors external dependencies, and introduces a provider session registry for SDK management. Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related issues
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
Replace the interactive menu with a CLI-first command surface, add shell completions, Rich dashboards, and substantially expand doctor diagnostics. Auto-detect plain mode from TTY state instead of requiring an explicit --plain flag. New commands: - `completions --shell bash|zsh|fish` emits sourcing scripts; zsh variant calls back into `polylogue _complete` for live suggestions (slugs, provider names, Drive chat IDs, session paths) - `dashboards` renders Rich provider-summary and recent-runs tables (or `--json` for machine consumption) - `runs` lists run history with `--providers`, `--commands`, `--since`/`--until` filters and Rich/plain/JSON output - `env` prints resolved config path, output directories, state/runs DB locations, and watchable providers (`--json` for scripts) - `help [COMMAND]` shows per-command argparse help plus a command listing table - `index check` validates SQLite FTS integrity and optionally Qdrant reachability, with `--repair` to rebuild missing tables CLI surface changes: - Remove `--plain` flag; plain mode auto-activates when stdout/stderr are not TTYs or `POLYLOGUE_FORCE_PLAIN=1` is set; `--interactive` re-enables prompts in headless shells - Remove `--branch-export` flag; branch layout is always full (canonical + common + per-branch directories) - Delete the interactive menu, settings menu, and all prompt_* functions from app.py (~400 lines); bare `polylogue` now prints help instead of launching a menu - Remove `automation` command, automation.py, automation_targets.json, and the NixOS module (nix/modules/polylogue.nix) - Remove structured stderr run logging (POLYLOGUE_RUN_LOG env var) - Add `--json-lines` to `status` for newline-delimited streaming Doctor enhancements (polylogue/doctor.py): - Check PATH for required CLI tools (gum, sk, bat, glow, delta) with hints pointing to `nix develop` - Verify config file presence with candidate-path hints - Check Drive credentials.json and token.json with OAuth hints - Run SQLite integrity + FTS table checks via index_health module - Probe Qdrant collection reachability when backend is configured - Issues now carry a `hint` field; Rich table output uses severity coloring Progress and retry UX: - Rich progress bars wrap Drive sync and local-sync session loops - Drive retry callback prints yellow retry/delay messages to console - Import/sync summaries include "Previous run" footer from util helpers (latest_run, format_run_brief) Infrastructure: - polylogue/providers/ package with ProviderRegistry protocol and DriveProviderSession wrapper around DriveClient - polylogue/_vendor/ fallbacks for frontmatter, pyperclip, and watchfiles when external packages are absent - polylogue/core/config_validation.py validates config at startup via Pydantic (rejects bad themes, non-numeric thresholds, unknown keys) - CompletionEngine (cli/completion_engine.py) resolves live completions from registrar state, argparse metadata, and provider session listings - nix/devshell.nix auto-sources the completion script for the active shell on entry Packaging: - Remove automation_targets.json from package-data in pyproject.toml - Delete flake.nix nixosModules export
There was a problem hiding this comment.
Pull request overview
This PR overhauls Polylogue’s CLI from an interactive-menu-first UX to a command-first interface, adding shell completions, richer operational visibility (dashboards/runs/env/index), improved doctor diagnostics, and startup config validation—while removing the automation/NixOS module and branch-export modes.
Changes:
- Add shell completions (bash/fish static, zsh dynamic via
_complete) plus new operational commands (dashboards,runs,env,help,index check). - Switch to automatic plain-mode detection (TTY +
POLYLOGUE_FORCE_PLAIN) and add Rich progress bars + better retry UX/diagnostics. - Simplify branching output to always “full tree” and remove automation/NixOS module paths and related tests/docs.
Reviewed changes
Copilot reviewed 72 out of 72 changed files in this pull request and generated 12 comments.
Show a summary per file
| File | Description |
|---|---|
| AGENTS.md | Updates repo guidelines to reflect command-first CLI + plain-mode detection. |
| README.md | Refreshes docs for new command-first UX, new commands, and removed automation/branch-export. |
| pyproject.toml | Removes package-data for deleted automation metadata. |
| flake.nix | Removes exported NixOS module wiring. |
| nix/devshell.nix | Auto-generates/sources shell completions on devshell entry. |
| nix/modules/polylogue.nix | Removes NixOS module (deleted). |
| docs/architecture.md | Updates architecture notes (no menu; mentions completion/registry). |
| docs/providers/openai-codex.md | Updates provider docs for fixed branch layout + sync notes. |
| docs/providers/gemini.md | Updates provider docs for fixed branch layout + Drive --chat-id. |
| docs/providers/claude-code.md | Updates provider docs for fixed branch layout + sync notes. |
| docs/providers/claude-ai.md | Updates provider docs for fixed branch layout + --session guidance. |
| docs/providers/chatgpt.md | Updates provider docs for fixed branch layout + --session guidance. |
| polylogue/cli/app.py | Implements command-first app surface, plain-mode detection, help/env/completions, and command registration. |
| polylogue/cli/completion_engine.py | Adds dynamic completion engine backing zsh _complete. |
| polylogue/cli/index_cli.py | Adds index check command (SQLite/Qdrant validation + JSON). |
| polylogue/index_health.py | Adds SQLite/Qdrant health verification helpers. |
| polylogue/cli/dashboards.py | Adds dashboards command (Rich panels + JSON mode). |
| polylogue/cli/runs.py | Adds runs command with filters and Rich/plain outputs. |
| polylogue/cli/status.py | Extends status with --json-lines and improved provider filtering. |
| polylogue/cli/doctor.py | Enhances doctor output (severity styling + hints, JSON includes hint). |
| polylogue/doctor.py | Adds dependency/config/credential/index/qdrant checks and hint support. |
| polylogue/core/config_validation.py | Adds Pydantic config validation models (extra=forbid). |
| polylogue/core/configuration.py | Validates config payload on load. |
| polylogue/ui/init.py | Adds progress tracker abstraction and updates UI creation flow. |
| polylogue/ui/facade.py | Hard-requires interactive toolchain in interactive mode (no silent fallback). |
| polylogue/cli/sync.py | Adds “previous run” UX, progress usage, and improved error surfacing. |
| polylogue/cli/render.py | Removes branch-export option from render CLI path. |
| polylogue/cli/watch.py | Uses watchfiles vendor hook and passes UI into local sync. |
| polylogue/cli/imports.py | Adds previous-run footer + improves Codex session selection UX. |
| polylogue/cli/summaries.py | Adds optional extra summary lines; uses Rich table directly when interactive. |
| polylogue/cli/context.py | Removes branch-export defaults from CLI default namespaces. |
| polylogue/cli/arg_helpers.py | Removes branch-export flag helper. |
| polylogue/cli/init.py | Exposes new CLI entrypoints (help/env/completions/dashboards/complete). |
| polylogue/cli/automation_cli.py | Removes automation CLI (deleted). |
| polylogue/automation.py | Removes automation snippet generator (deleted). |
| polylogue/automation_targets.json | Removes automation target metadata (deleted). |
| polylogue/conversation.py | Removes branch-export modes; always writes full branch tree. |
| polylogue/options.py | Removes branch_export from options dataclasses. |
| polylogue/local_sync.py | Adds UI progress support; removes branch_mode plumbing. |
| polylogue/commands.py | Adds provider registry + Drive session registration; adds Drive sync progress. |
| polylogue/providers/registry.py | Introduces ProviderRegistry + ProviderSession protocol. |
| polylogue/providers/drive.py | Adds DriveProviderSession wrapper around DriveClient. |
| polylogue/providers/init.py | Exports provider registry/session types. |
| polylogue/drive.py | Adds retry notifier hook plumbing. |
| polylogue/drive_client.py | Wires retry notifier into Drive operations. |
| polylogue/util.py | Adds latest_run/format_run_brief; removes structured stderr run log; updates clipboard import path. |
| polylogue/render.py | Switches to vendored frontmatter fallback path. |
| polylogue/document_store.py | Switches to vendored frontmatter fallback path. |
| polylogue/_vendor/init.py | Adds vendor package marker. |
| polylogue/_vendor/frontmatter.py | Adds minimal frontmatter implementation fallback. |
| polylogue/_vendor/pyperclip.py | Adds in-memory pyperclip stub fallback. |
| polylogue/_vendor/watchfiles.py | Adds watchfiles stub that raises at runtime. |
| polylogue/importers/codex.py | Removes branch_mode parameter plumbing. |
| polylogue/importers/claude_code.py | Removes branch_mode parameter plumbing. |
| polylogue/importers/claude_ai.py | Removes branch_mode parameter plumbing. |
| polylogue/importers/chatgpt.py | Removes branch_mode parameter plumbing. |
| tests/conftest.py | Adjusts sys.path bootstrapping. |
| tests/test_cli_help_env.py | Adds tests for help/env/completions/complete. |
| tests/test_dashboards.py | Adds dashboards JSON test coverage. |
| tests/test_runs_cli.py | Adds runs CLI test coverage (filters, since/until, JSON). |
| tests/test_index_cli.py | Adds index check CLI JSON test coverage. |
| tests/test_index_health.py | Adds sqlite index health test coverage. |
| tests/test_config_validation.py | Adds config validation tests. |
| tests/test_cli_flags.py | Adds sync selection tests and local sessions pass-through coverage. |
| tests/test_status.py | Adds --json-lines coverage and payload assertions. |
| tests/test_util_runs.py | Updates run persistence tests and adds latest/brief formatting coverage. |
| tests/test_watch_cli.py | Ensures watch errors surface (no silent fallback). |
| tests/test_render_branch.py | Removes canonical/overlay branch-export tests; keeps full-tree assertion. |
| tests/test_branch_and_search.py | Removes branch-export-mode tests. |
| tests/test_cli_integration.py | Updates for POLYLOGUE_FORCE_PLAIN and removes Rich skipifs. |
| tests/test_ui.py | Removes Rich skipifs (Rich now hard-required). |
| tests/test_automation_snippets.py | Removes automation snippet tests (deleted). |
Comments suppressed due to low confidence (1)
polylogue/cli/render.py:78
- This CLI pre-initializes env.drive with DriveClient(ui). That bypasses CommandEnv.drive_constructor injection and the DriveProviderSession wrapper/registration done by commands._ensure_drive(). Since render_command() already calls _ensure_drive() when download_attachments is enabled, consider removing this direct instantiation (or using env.drive_constructor via _ensure_drive) to keep Drive session handling consistent.
if download_attachments and env.drive is None:
env.drive = DriveClient(ui)
result = render_command(options, env)
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| def verify_sqlite_indexes(db_path: Path = DB_PATH, *, attempt_rebuild: bool = True) -> List[str]: | ||
| issues: List[str] = [] | ||
| conn = sqlite3.connect(db_path) | ||
| try: | ||
| status = conn.execute("PRAGMA integrity_check").fetchone()[0] | ||
| if status != "ok": |
There was a problem hiding this comment.
verify_sqlite_indexes() uses sqlite3.connect(db_path) directly, so it won’t ensure the DB directory exists or apply the canonical schema/PRAGMAs from db.open_connection(). This can create an incomplete DB file (or fail when the parent dir is missing). Consider using open_connection(db_path) here (or at least mkdir + PRAGMA foreign_keys) so schema invariants match the rest of the codebase.
| if "no such table" in message: | ||
| conn.execute( | ||
| """ | ||
| CREATE VIRTUAL TABLE IF NOT EXISTS messages_fts USING fts5( | ||
| provider, | ||
| conversation_id, | ||
| branch_id, | ||
| message_id, | ||
| content, | ||
| tokenize='unicode61' | ||
| ) | ||
| """ | ||
| ) | ||
| issues.append("messages_fts table was missing; recreated") | ||
| elif attempt_rebuild: | ||
| conn.execute("INSERT INTO messages_fts(messages_fts) VALUES('rebuild')") | ||
| issues.append("Rebuilt messages_fts index") | ||
| else: | ||
| raise | ||
| conn.commit() |
There was a problem hiding this comment.
When messages_fts is missing, verify_sqlite_indexes() recreates the FTS table but never repopulates it from the existing messages table. That leaves search empty until every conversation is re-ingested. After recreating, consider repopulating with the same INSERT INTO messages_fts ... SELECT ... FROM messages pattern used in db.replace_messages(), or trigger a full rebuild that actually reindexes existing content.
| try: | ||
| sqlite_notes = verify_sqlite_indexes(DB_PATH) | ||
| if sqlite_notes: | ||
| counts["indexes"] = counts.get("indexes", 0) + len(sqlite_notes) | ||
| for note in sqlite_notes: | ||
| issues.append(DoctorIssue("index", DB_PATH, note, "info")) | ||
| except Exception as exc: |
There was a problem hiding this comment.
run_doctor() calls verify_sqlite_indexes(DB_PATH) with the default attempt_rebuild=True, so polylogue doctor may mutate/repair the SQLite index as a side effect. The PR description frames repair as an explicit index check --repair action; consider calling verify_sqlite_indexes(..., attempt_rebuild=False) from doctor (and only rebuilding from the dedicated index command).
| for msg in report["qdrant"]["messages"]: | ||
| lines.append(f" - {msg}") | ||
| else: | ||
| lines.append("Qdrant index: skipped (use --skip-qdrant to suppress)") |
There was a problem hiding this comment.
The human-readable output says Qdrant index: skipped (use --skip-qdrant to suppress), but this branch is only reached because --skip-qdrant was set. The hint is inverted; it should indicate how to enable/disable the check (e.g., “skipped (pass --skip-qdrant to skip)” or just “skipped”).
| lines.append("Qdrant index: skipped (use --skip-qdrant to suppress)") | |
| lines.append("Qdrant index: skipped") |
| try: | ||
| import pyperclip | ||
| from pyperclip import PyperclipException | ||
| except ImportError: | ||
| from ._vendor import pyperclip # type: ignore | ||
| from ._vendor.pyperclip import PyperclipException # type: ignore | ||
|
|
There was a problem hiding this comment.
This file adds vendored fallbacks for pyperclip when the import fails. That conflicts with the repo guideline to hard-require dependencies (AGENTS.md:13-14) and pyproject.toml lists pyperclip as a required dependency. Consider removing the vendored fallback and letting the import fail (or treating missing deps as a hard error) so behavior stays consistent with the declared dependency contract.
| def names(self) -> Dict[str, ProviderDescriptor]: | ||
| return dict(self._providers) |
There was a problem hiding this comment.
ProviderRegistry.names() returns a dict of ProviderDescriptor objects, which is surprising given the method name (and contrasts with CommandRegistry.names() returning a List[str]). Consider renaming this to something like descriptors()/items(), or changing the return type to List[str] if the intent is to expose just provider names.
| from pathlib import Path | ||
| from typing import Dict, List, Optional | ||
|
|
||
| from typing import Callable | ||
|
|
There was a problem hiding this comment.
DriveProviderSession has redundant typing imports (Dict/List/Optional plus a separate from typing import Callable) and the order is inconsistent. Consolidating these into a single from typing import ... keeps imports tidy and avoids lint noise.
| try: | ||
| import frontmatter | ||
| except ImportError: # pragma: no cover | ||
| frontmatter = None | ||
| except ImportError: | ||
| from ._vendor import frontmatter # type: ignore |
There was a problem hiding this comment.
This module now falls back to a vendored frontmatter implementation when python-frontmatter isn’t importable. That conflicts with the repo guideline to hard-require dependencies (AGENTS.md:13-14) and python-frontmatter is listed as a required dependency in pyproject.toml. Consider removing the fallback and letting the import fail loudly if dependencies are missing.
| try: | ||
| import frontmatter # type: ignore | ||
| except ImportError: # pragma: no cover | ||
| frontmatter = None | ||
| except ImportError: | ||
| from ._vendor import frontmatter # type: ignore | ||
|
|
There was a problem hiding this comment.
This module now falls back to a vendored frontmatter implementation when python-frontmatter isn’t importable. That conflicts with the repo guideline to hard-require dependencies (AGENTS.md:13-14) and python-frontmatter is listed as a required dependency in pyproject.toml. Consider removing the fallback and letting the import fail loudly if dependencies are missing.
| try: | ||
| from watchfiles import watch as _watch_directory | ||
| except ImportError: # pragma: no cover - used in non-watch environments | ||
| def _watch_directory(*_args, **_kwargs): | ||
| yield from () | ||
| except ImportError: # pragma: no cover - fallback for environments without watchfiles | ||
| from .._vendor.watchfiles import watch as _watch_directory | ||
|
|
There was a problem hiding this comment.
This fallback to a vendored watchfiles implementation conflicts with the repo guideline to hard-require dependencies (AGENTS.md:13-14), and watchfiles is listed as a required dependency in pyproject.toml. Consider removing the fallback and letting the import error surface so missing dependencies fail fast.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 84d389ea30
ℹ️ 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: 44
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
polylogue/ui/facade.py (1)
110-114: 🧹 Nitpick | 🔵 TrivialRemove dead code:
TextandPanelare now always available.Since Rich imports are no longer conditional (lines 10-12),
Text is not NoneandPanel is not Nonewill always be true. These checks are now dead code.♻️ Proposed fix to remove dead code
def _interactive_summary(self, title: str, text: str) -> None: result = subprocess.run( ["gum", "format"], input=f"## {title}\n{text}\n", text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True, ) output = result.stdout.rstrip() if output: self.console.print(output, markup=False, highlight=False) return - renderable = Text(text) if Text is not None else text - if Panel is not None: - self.console.print(Panel(renderable, title=title)) - else: - self.console.print(f"{title}\n{text}") + self.console.print(Panel(Text(text), title=title))🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@polylogue/ui/facade.py` around lines 110 - 114, The checks for Text and Panel are dead code; update the render logic in facade.py to always use Rich's Text and Panel: create renderable = Text(text) (no conditional), and always call self.console.print(Panel(renderable, title=title)) instead of branching to the fallback print; adjust any related variables (renderable, title) accordingly and remove the now-unnecessary branches referencing Text is not None or Panel is not None.polylogue/drive.py (1)
286-294:⚠️ Potential issue | 🟡 MinorPropagate
notifierin the primary folder lookup path.
find_folder_id(..., notifier=...)forwards notifier for cached-ID validation, but not for the fallback folder search query. That creates inconsistent retry UX.🔧 Proposed fix
resp = _drive_get_json( session, "files", { "q": f"mimeType='application/vnd.google-apps.folder' and name='{escaped_name}' and trashed=false", "fields": "files(id, name, modifiedTime)", "pageSize": 50, }, + notifier=notifier, )🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@polylogue/drive.py` around lines 286 - 294, The fallback folder search in find_folder_id doesn't use the notifier, causing inconsistent retry behavior; update the primary lookup path so the _drive_get_json call that sets resp (the "files" search) is invoked with the same notifier used for cached-ID validation (i.e., propagate the notifier argument through to _drive_get_json or the helper it calls), ensuring the "files" query uses notifier for retries and logging; locate find_folder_id and the resp = _drive_get_json(...) call and add the notifier parameter propagation so both cached-ID validation and fallback search share the notifier.polylogue/doctor.py (1)
96-96:⚠️ Potential issue | 🟡 MinorAdd missing
Anytype import.Line 96 uses
Dict[str, Dict[str, Any]]butAnyis not imported fromtypingon line 7.🔧 Proposed fix
-from typing import Dict, List, Optional, Tuple +from typing import Any, Dict, List, Optional, Tuple🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@polylogue/doctor.py` at line 96, The file uses the type Any in the declaration aggregates: Dict[str, Dict[str, Any]] but Any is not imported; update the typing imports at the top of polylogue/doctor.py (where Dict is imported) to include Any so that the aggregates type annotation and any other uses of Any resolve correctly.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@AGENTS.md`:
- Around line 11-20: Add a blank line immediately after the headings "##
Development Workflow" and "## Automation & Testing" so each heading is followed
by an empty line before the subsequent list items (this addresses markdownlint
rule MD022 and prevents docs checks from failing); locate the two headings in
AGENTS.md and insert one newline between the heading line and the first list
item under each section.
In `@docs/providers/chatgpt.md`:
- Line 25: The docs still reference the old layout: remove or update the stale
wording that says the canonical transcript lives at `<slug>.md` and rename the
misleading section heading “Modes” to reflect the fixed tree; instead document
that `polylogue import chatgpt` always writes the canonical transcript alongside
`conversation.common.md` and per-branch files under
`branches/<branch-id>/{<branch-id>.md, overlay.md}` so there is a single,
consistent layout and no alternate `<slug>.md` placement.
In `@docs/providers/claude-code.md`:
- Around line 24-26: Update the outdated header "Branch Export Modes" to reflect
the single fixed layout (e.g., "Branch Export Layout" or "Branch Export (Fixed
Layout)") and ensure any internal references or cross-links use the new header
text; keep the body as-is that documents conversation.md,
conversation.common.md, and branches/<branch-id>/{<branch-id>.md, overlay.md} to
match the header change.
In `@nix/devshell.nix`:
- Around line 46-56: The current init uses predictable temp filenames and
blindly sources them even when generation may have failed; change the logic
around _polylogue_comp_file and the call to "python3 polylogue.py completions
--shell ..." to create a unique temp file (e.g., via mktemp or similar), ensure
TMPDIR has a safe default if unset, run the completions command and capture its
exit status, and only source the temp file when the command succeeded and the
file exists; update the bash/zsh/fish blocks that set _polylogue_comp_file and
source it (and remove the "|| true" suppressor) so stale or untrusted content
cannot be sourced.
In `@polylogue/_vendor/frontmatter.py`:
- Around line 33-41: The current frontmatter parsing only strips double quotes;
update the conditional that checks quoted strings to handle matching single
quotes as well by detecting whether value starts and ends with the same quote
character (either " or '), e.g. test the first char and ensure the last char
equals it, then set metadata[key] = value[1:-1]; keep the existing boolean check
(value.lower() in {"true","false"}) and the json.loads fallback untouched so
single-quoted values are treated as quoted strings rather than passed to
json.loads or stored with surrounding quotes.
- Around line 18-25: The frontmatter parsing loop currently assumes a closing
'---' was found and always sets body = "\n".join(lines[i:]), which discards
content when the delimiter is missing; modify the loop to track whether the
closing delimiter was found (e.g., found_close boolean set true inside the if
block that breaks), and after the loop if found_close is False reconstruct body
from the collected meta_lines plus remaining lines (e.g., body =
"\n".join(meta_lines + lines[i:])) and clear meta_lines, otherwise keep the
existing behavior; refer to the variables meta_lines, lines, body and the loop
index i when making this change.
In `@polylogue/_vendor/pyperclip.py`:
- Around line 16-22: The in-memory fallback in pyperclip.py (functions copy and
paste using _CLIPBOARD) must not silently succeed in production; change
copy(text) and paste() to raise PyperclipException when no real clipboard
backend is available (referencing PyperclipException and _CLIPBOARD) or gate the
fallback behind an explicit test-only flag (e.g., an environment variable or a
module-level ENABLE_TEST_FALLBACK) so production consumers like
util.write_clipboard_text() get an exception instead of a false success; update
the logic so the fallback is only used when the test flag is set and otherwise
raise PyperclipException to preserve the expected error-handling contract.
In `@polylogue/cli/app.py`:
- Around line 102-108: The function _collect_subparser_map currently relies on
the private attribute parser._actions and checking for
argparse._SubParsersAction; replace the direct access with a safe
public-friendly approach by using getattr(parser, "_actions", []) to avoid
AttributeError on unexpected parser implementations, keep the existing
isinstance(action, argparse._SubParsersAction) check and action.choices usage,
and add a fallback (empty mapping) or a clear error if no actions are present so
the function behaves safely when the private attribute is unavailable.
- Around line 232-241: The run_completions_cli function currently declares an
unused parameter env; rename it to _env to signal it's intentionally unused and
satisfy the standard handler signature (i.e., change the function signature from
def run_completions_cli(args: argparse.Namespace, env: CommandEnv) -> None: to
def run_completions_cli(args: argparse.Namespace, _env: CommandEnv) -> None:),
leaving the body (parser = build_parser(), _command_entries,
_zsh_dynamic_script, _completion_script, print(script)) unchanged.
- Around line 877-878: The two lambda wrappers are redundant; instead of
_ensure("runs", lambda args, env: run_runs_cli(args, env), ...) and
_ensure("index", lambda args, env: run_index_cli(args, env), ...), pass the
callables directly by using run_runs_cli and run_index_cli as the second
argument to _ensure (i.e., _ensure("runs", run_runs_cli, "List recent runs") and
_ensure("index", run_index_cli, "Index maintenance helpers")), ensuring the
function signatures of run_runs_cli and run_index_cli match the expected (args,
env) parameters.
- Around line 1083-1088: The p_index_check subparser is created via
index_sub.add_parser() instead of using the helper _add_command_parser which
applies the ArgumentDefaultsHelpFormatter; change the creation of the "check"
subcommand to call _add_command_parser(index_sub, "check", help="Validate
SQLite/Qdrant indexes") (and include the same arguments/description) so that the
p_index_check parser (used for adding --repair, --skip-qdrant, --json) gets the
same formatter behavior as other subparsers.
- Around line 279-287: The call create_ui(True) in run_complete_cli is using a
positional boolean which hurts readability; update it to pass the boolean as a
keyword argument using the actual parameter name from create_ui's signature
(e.g., if the parameter is named raw or enabled, call create_ui(raw=True) or
create_ui(enabled=True)), and keep the rest of the code (CommandEnv(ui=...))
unchanged so intent is explicit.
- Around line 193-202: The code reassigns the variable entries from a List[str]
to a str (entries = "\n".join(entries)), which is confusing; preserve the list
type by keeping entries as List[str] and use a new variable (e.g., entries_str
or result) for the joined string, then return that variable.strip(); update the
function that builds completion lines (the entries list construction block) to
join into a new variable instead of mutating entries so static analyzers and
readers see consistent types for entries.
In `@polylogue/cli/completion_engine.py`:
- Line 38: The complete method currently declares an unused parameter shell;
either remove it or explicitly mark it unused. Simplest fix: remove shell from
the complete(self, cword: int, words: Sequence[str]) -> List[Completion]
signature in the CompletionEngine (and any subclass overrides) and update all
call sites that pass a shell argument to stop passing it; alternatively, if you
must keep the param for API compatibility, rename it to _shell (or prefix with
_) in the complete method and any overrides to silence linter warnings and make
intent clear. Ensure method signatures remain consistent across
subclasses/overrides (complete) and update type hints/docs accordingly.
- Around line 102-112: The _complete_import function references current_word
which is undefined; fix by deriving current_word from the args and current_index
(e.g., set current_word = args[current_index] if current_index < len(args) else
"") or by adding a current_word parameter to _complete_import and passing it
from the caller; update the caller(s) that invoke _complete_import (the
completion dispatch that currently calls _complete_import) to supply the new
argument if you choose the parameter approach, and then use that current_word in
the existing condition (if current_word.startswith("--")) so the NameError is
eliminated.
- Around line 134-142: The helper _complete_watch currently references an
undefined variable current_word; update its signature to accept current_word
(e.g., def _complete_watch(self, args: Sequence[str], current_index: int,
current_word: str) -> List[Completion]) and use that parameter instead of the
undefined name, then update any call sites that invoke _complete_watch (such as
where it's called around line 64) to pass the current_word argument; ensure you
adjust type hints and imports if needed and preserve existing behavior for
options and path completions in _complete_watch.
In `@polylogue/cli/dashboards.py`:
- Around line 19-25: The table consumer is using info.get("runs", 0) while the
upstream schema uses "count" for run totals, so the "Runs" column shows 0;
update the table.add_row call in dashboards.py to read the correct keys from
provider_summary (use info.get("count", 0) for the Runs column and keep the
existing info.get("attachments", 0) and info.get("failures", 0) usages), or
alternatively ensure both "runs" and "count" are populated upstream if you
prefer the new key—reference the provider_summary variable and the table.add_row
invocation when making the change.
In `@polylogue/cli/doctor.py`:
- Around line 8-9: The table cells are populated from data-derived values
(issue.path, issue.message, issue.hint) which may contain brackets and get
interpreted as Rich markup; import and use rich.markup.escape and pass
escape(issue.path), escape(issue.message), and escape(issue.hint) (or otherwise
disable markup when constructing Text) when calling table.add_row (or wherever
rows are added) to ensure the text is escaped before adding to the Table.
In `@polylogue/cli/imports.py`:
- Around line 177-191: The interactive sentinel values are inconsistent between
Codex and Claude Code; define a shared constant (e.g. INTERACTIVE_SENTINELS =
{None, "", "pick", "?", "-"}) and replace the per-provider checks with
membership tests against that constant (update the check that references
session_target in the Codex branch and the analogous check in the Claude Code
branch), ensuring you still respect the existing ui.plain gating and the
fallback/empty-case handling (the variables to change are session_target and any
provider-specific sentinel checks).
In `@polylogue/cli/index_cli.py`:
- Around line 52-53: The "Qdrant index: skipped (use --skip-qdrant to suppress)"
message is misleading because it tells the user to use --skip-qdrant even when
the index is already skipped; update the else branch that appends the "Qdrant
index: skipped" line in index_cli.py to remove or replace the hint with a
correct one (e.g., "Qdrant index: skipped (use --qdrant to enable)" or "Qdrant
index: skipped (omit --skip-qdrant to enable)"), locating the code that appends
to the lines list where the string "Qdrant index: skipped" is constructed and
change the hint text accordingly.
- Around line 26-37: The Qdrant check currently only catches RuntimeError,
causing other exceptions from verify_qdrant_collection to bubble up; change the
except clause to catch Exception (like the SQLite block) and update
report["qdrant"]["status"] to "error" and append str(exc) to
report["qdrant"]["messages"] so all errors are recorded; ensure you still
respect args.skip_qdrant via getattr(args, "skip_qdrant", False) and mirror the
SQLite error-handling pattern for consistency.
In `@polylogue/cli/runs.py`:
- Around line 75-90: _timestamp_in_range currently swallows parsing errors and
defaults to True, which hides malformed timestamps; update the function to catch
the parse exception, emit a debug log (use the module logger) that includes the
problematic timestamp and exception, and then decide whether to include or
exclude (keep current behavior if you must but log it). Also simplify the final
return logic in _timestamp_in_range by replacing the successive if checks for
since/until with a single boolean expression that returns False if (since is not
None and epoch < since) or (until is not None and epoch > until), otherwise
True, so the function is clearer and more concise.
- Around line 64-72: The plain-text printer _print_plain currently omits the
"retries" and "failures" fields present in the Rich table; update _print_plain
to include retries and failures in the printed line (use entry.get('retries', 0)
and entry.get('failures', 0)) so the plain output matches the table output
format and shows provider, count, duration, retries and failures for each entry.
In `@polylogue/cli/status.py`:
- Around line 81-88: The _matches function currently treats empty provider
values as a match when provider_filter is set; update it so that when
provider_filter is truthy it only returns True for non-empty provider strings
that are present in provider_filter. Specifically, in the _matches(record: dict)
function (used to build filtered_recent_runs and filtered_runs), replace the
final return logic with a check that provider_value is non-empty and
provider_value in provider_filter (i.e., return bool(provider_value) and
provider_value in provider_filter), leaving the behaviour unchanged when
provider_filter is falsy.
In `@polylogue/commands.py`:
- Around line 674-682: The current try-except-pass around os.utime calls for
result.markdown_path and result.html_path silently swallows all errors; replace
these blocks with contextlib.suppress(OSError) to cleanly ignore expected
filesystem errors and add a debug-level log via the existing logger (or
processLogger) when an exception is suppressed so permission/IO issues are
recorded for troubleshooting; specifically update the os.utime calls for
result.markdown_path and result.html_path in the function containing them to use
contextlib.suppress and logger.debug including the path and exception
information.
In `@polylogue/conversation.py`:
- Around line 159-161: The unconditional flags write_branch_tree,
write_full_branch_docs, and write_overlay_docs mean older conversations may lack
branch artifacts but persist_result.skipped is still true, so modify the skip
logic to detect missing branch artifacts and force a write (set
persist_result.skipped = False) or trigger a repair/migration path;
specifically, before honoring persist_result.skipped check for the presence of
branch tree/full-branch docs/overlay docs for the conversation (the artifacts
referenced by write_branch_tree/write_full_branch_docs/write_overlay_docs) and
treat any missing artifact as a reason not to skip so the branch-writing block
runs and backfills the missing data.
In `@polylogue/core/config_validation.py`:
- Around line 17-18: Replace the deprecated Pydantic v1 nested "class Config"
blocks in this file with Pydantic v2 style by adding a module-level import
"ConfigDict" from pydantic and setting model_config = ConfigDict(extra="forbid")
on each Pydantic model instead of defining class Config; locate the models that
currently nest "class Config" (the three models referenced) and remove that
inner class, adding the model_config assignment to each model class so they use
Pydantic v2 configuration.
- Around line 43-48: The `@model_validator`(mode="after") decorated function
ensure_theme currently uses a classmethod signature (cls, values) which is
invalid for "after" validators; change it to an instance method that accepts the
model instance (e.g., def ensure_theme(self, model: "ConfigModel") ->
"ConfigModel":), read theme from model.defaults (theme =
model.defaults.html_theme if model.defaults else None), perform the same check
and raise, and return the model; keep the decorator as
`@model_validator`(mode="after") and the function name ensure_theme to locate the
change.
In `@polylogue/core/configuration.py`:
- Around line 112-113: The validation gate currently skips
validate_config_payload when data is falsy (e.g., empty list), so change the
conditional to call validate_config_payload whenever a payload was provided
(check data is not None rather than truthiness) or otherwise explicitly handle
allowed empty structures; update the block that references the variable data to
call validate_config_payload(data) for any non-None payload so falsy-but-invalid
payloads like [] are validated by validate_config_payload.
In `@polylogue/document_store.py`:
- Around line 48-50: Modify _parse_front_matter to catch exceptions from
frontmatter.loads so malformed YAML doesn't abort import; when frontmatter.loads
raises, return an empty metadata dict and the original text as content. Update
the function implementation (referencing _parse_front_matter and callers like
read_existing_document and persist_document) to swallow parsing errors,
optionally logging if a logger exists, and ensure callers continue to run
dirty-detection logic even when front matter is invalid.
In `@polylogue/drive_client.py`:
- Around line 50-53: The error message in ensure_credentials() incorrectly tells
users to place credentials next to polylogue.py; update the SystemExit text to
reference the actual locations checked (the environment variable
DRIVE_CREDENTIAL_ENV and the path in self._credentials_path) so it instructs
users to set $POLYLOGUE_DRIVE_CREDENTIALS or place their credentials file at the
configured self._credentials_path; mention both symbols (DRIVE_CREDENTIAL_ENV
and self._credentials_path) in the message and provide a brief actionable phrase
about how to obtain a Google OAuth client secret.
In `@polylogue/index_health.py`:
- Around line 11-44: The verify_sqlite_indexes function currently tries INSERT
INTO messages_fts(...) when attempt_rebuild is true, which can fail if the FTS
table is actually missing or the OperationalError message format differs; change
the flow so that after catching sqlite3.OperationalError you explicitly check
for the messages_fts table existence (e.g., query sqlite_master for a table
named 'messages_fts') and if it does not exist create the virtual FTS table
(using the same schema in the current CREATE VIRTUAL TABLE block), otherwise
perform the rebuild INSERT; ensure you only attempt the INSERT rebuild when the
table is confirmed to exist, still honor attempt_rebuild flag, commit on
success, and re-raise unexpected errors.
In `@polylogue/local_sync.py`:
- Around line 99-108: The _NoopProgress class duplicates functionality of the
existing _NullProgressTracker in polylogue.ui; remove the local _NoopProgress
definition and replace its usages to reuse the existing implementation (either
import _NullProgressTracker from polylogue.ui or obtain the tracker via
ui.progress() / UI.progress()) so the code uses _NullProgressTracker (or
ui.progress()) instead of defining a new no-op progress class.
- Around line 141-147: Remove the redundant list() calls: when building iterable
from sessions, call sorted(...) directly on the generator/iterable (using
Path(p) with key=path_order_key) instead of wrapping sessions in list(); and
assign session_list directly from the result of sorted(...) (no list(iterable)
copy). Update the variables referenced (sessions, iterable, session_list) in
polylogue/local_sync.py so sorted is used once to produce the ordered list for
progress_ctx (keep ui.progress usage unchanged).
In `@polylogue/providers/drive.py`:
- Around line 25-27: The __getattr__ in DriveProviderSession currently delegates
to self._client without handling missing attributes; wrap the
getattr(self._client, item) call in a try/except catching AttributeError and
re-raise a new AttributeError that mentions DriveProviderSession and the missing
attribute name (item) to produce a clearer error message while preserving the
original exception context where appropriate.
In `@polylogue/providers/registry.py`:
- Around line 14-17: ProviderDescriptor currently duplicates
ProviderSession.name; remove the redundant name field from the
ProviderDescriptor dataclass and update any construction/usage to rely on
session.name instead. Specifically, delete the `name: str` attribute from
ProviderDescriptor, update the `register` function (and any other callers) to
not pass a separate name but use `session.name` when a descriptor name is
needed, and adjust any attribute access from `descriptor.name` to
`descriptor.session.name` (or cache `session.name` into descriptor only where
absolutely necessary).
- Around line 33-34: The method names() returns Dict[str, ProviderDescriptor]
(wrapping self._providers) but its name is misleading; rename names to
descriptors (or all_descriptors) and update its signature and any callers to use
descriptors() returning Dict[str, ProviderDescriptor]; ensure the new method
still returns dict(self._providers) and update any docstrings, type hints, and
unit tests/references that called names() so they use descriptors() instead;
alternatively, if you prefer keeping the name, change the return to List[str] by
returning list(self._providers.keys()) and update callers accordingly (choose
one approach and make consistent updates across the codebase).
In `@polylogue/ui/__init__.py`:
- Around line 124-135: The __enter__ method on class _NullProgressTracker lacks
an explicit return type; annotate it to return Self (or "_NullProgressTracker"
if typing.Self is unavailable) so context-manager usage is properly typed—update
the signature of _NullProgressTracker.__enter__ to include the return type and
import typing.Self or use the class name as the return annotation.
In `@polylogue/util.py`:
- Around line 184-192: The latest_run function currently calls load_runs() which
loads all runs into memory then filters in Python; change this to perform
filtering at the data source by adding SQL-level filtering or a dedicated query
method and calling that from latest_run. Specifically, modify or add a function
(e.g., query_runs or load_runs with optional provider/cmd params) that accepts
provider and cmd and returns an iterator or ordered result set from the
database, then have latest_run call that filtered query (or use the DB ORDER BY
/ LIMIT logic) to return only the most recent matching entry instead of loading
all runs into memory; update references to load_runs and latest_run accordingly.
In `@README.md`:
- Line 21: The README contains a typo in the default output path: change any
occurrence of "~/polyologue-data/claude" to the correct
"~/polylogue-data/claude" in the descriptive sentence under the "Sync provider
archives" section (the line that lists defaults and mentions `polylogue.config`
and paths such as `~/polylogue-data/sync-drive`, `~/polylogue-data/codex`,
etc.); ensure all similar misspellings of "polyologue" in that paragraph are
replaced with "polylogue" so paths and examples are consistent with the project
name and config.
In `@tests/test_cli_help_env.py`:
- Around line 40-46: The test passes an argparse.Namespace without an explicit
topic which can be unclear; update test_help_lists_command_descriptions to pass
argparse.Namespace(topic=None) so the intent that no topic is provided is
explicit and to ensure run_help_cli is exercised with a missing topic value
(refer to run_help_cli and the
test_help_lists_command_descriptions/argparse.Namespace usage to locate the
change).
In `@tests/test_index_health.py`:
- Around line 16-17: The test currently only checks the returned notes from
verify_sqlite_indexes(db_path) but not that the FTS object was actually created;
after calling verify_sqlite_indexes, open the same SQLite database and query
sqlite_master for an object named "messages_fts" (e.g., SELECT name FROM
sqlite_master WHERE name='messages_fts') and assert that the query returns a row
so the test proves the rebuild actually happened; reference the existing
verify_sqlite_indexes call and the "messages_fts" name when adding the
sqlite_master assertion.
In `@tests/test_status.py`:
- Around line 170-172: The test currently only checks that payload startswith
"{" and endswith "}" (using payload and json.loads(payload)), which allows
multi-line JSON; update the assertion to enforce single-line output by verifying
the captured payload from capsys.readouterr() contains no newline characters
(e.g., assert "\n" not in payload or payload.count("\n") == 0) or by comparing
payload to a compact serialization of the parsed object (json.dumps(data)); make
this change around the payload / data handling to ensure the JSON is a single
line.
In `@tests/test_util_runs.py`:
- Around line 20-26: The test test_add_run_persists_metadata should also assert
the serialized "out" value to catch regressions: after calling util.add_run(...)
and loading payload via util.load_runs(...), add an assertion that
payload["out"] equals the expected serialized path (e.g., str(tmp_path / "out"))
so the non-primitive field persisted correctly; update the existing
test_add_run_persists_metadata to include this extra assertion referencing
payload and util.add_run / util.load_runs.
---
Outside diff comments:
In `@polylogue/doctor.py`:
- Line 96: The file uses the type Any in the declaration aggregates: Dict[str,
Dict[str, Any]] but Any is not imported; update the typing imports at the top of
polylogue/doctor.py (where Dict is imported) to include Any so that the
aggregates type annotation and any other uses of Any resolve correctly.
In `@polylogue/drive.py`:
- Around line 286-294: The fallback folder search in find_folder_id doesn't use
the notifier, causing inconsistent retry behavior; update the primary lookup
path so the _drive_get_json call that sets resp (the "files" search) is invoked
with the same notifier used for cached-ID validation (i.e., propagate the
notifier argument through to _drive_get_json or the helper it calls), ensuring
the "files" query uses notifier for retries and logging; locate find_folder_id
and the resp = _drive_get_json(...) call and add the notifier parameter
propagation so both cached-ID validation and fallback search share the notifier.
In `@polylogue/ui/facade.py`:
- Around line 110-114: The checks for Text and Panel are dead code; update the
render logic in facade.py to always use Rich's Text and Panel: create renderable
= Text(text) (no conditional), and always call
self.console.print(Panel(renderable, title=title)) instead of branching to the
fallback print; adjust any related variables (renderable, title) accordingly and
remove the now-unnecessary branches referencing Text is not None or Panel is not
None.
🪄 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: 761c2ac3-d136-4d44-9b37-d4b96d0be027
📒 Files selected for processing (72)
AGENTS.mdREADME.mddocs/architecture.mddocs/providers/chatgpt.mddocs/providers/claude-ai.mddocs/providers/claude-code.mddocs/providers/gemini.mddocs/providers/openai-codex.mdflake.nixnix/devshell.nixnix/modules/polylogue.nixpolylogue/_vendor/__init__.pypolylogue/_vendor/frontmatter.pypolylogue/_vendor/pyperclip.pypolylogue/_vendor/watchfiles.pypolylogue/automation.pypolylogue/automation_targets.jsonpolylogue/cli/__init__.pypolylogue/cli/app.pypolylogue/cli/arg_helpers.pypolylogue/cli/automation_cli.pypolylogue/cli/completion_engine.pypolylogue/cli/context.pypolylogue/cli/dashboards.pypolylogue/cli/doctor.pypolylogue/cli/imports.pypolylogue/cli/index_cli.pypolylogue/cli/render.pypolylogue/cli/runs.pypolylogue/cli/status.pypolylogue/cli/summaries.pypolylogue/cli/sync.pypolylogue/cli/watch.pypolylogue/commands.pypolylogue/conversation.pypolylogue/core/config_validation.pypolylogue/core/configuration.pypolylogue/doctor.pypolylogue/document_store.pypolylogue/drive.pypolylogue/drive_client.pypolylogue/importers/chatgpt.pypolylogue/importers/claude_ai.pypolylogue/importers/claude_code.pypolylogue/importers/codex.pypolylogue/index_health.pypolylogue/local_sync.pypolylogue/options.pypolylogue/providers/__init__.pypolylogue/providers/drive.pypolylogue/providers/registry.pypolylogue/render.pypolylogue/ui/__init__.pypolylogue/ui/facade.pypolylogue/util.pypyproject.tomltests/conftest.pytests/test_automation_snippets.pytests/test_branch_and_search.pytests/test_cli_flags.pytests/test_cli_help_env.pytests/test_cli_integration.pytests/test_config_validation.pytests/test_dashboards.pytests/test_index_cli.pytests/test_index_health.pytests/test_render_branch.pytests/test_runs_cli.pytests/test_status.pytests/test_ui.pytests/test_util_runs.pytests/test_watch_cli.py
💤 Files with no reviewable changes (15)
- polylogue/cli/render.py
- tests/test_ui.py
- polylogue/options.py
- pyproject.toml
- polylogue/importers/codex.py
- polylogue/importers/claude_code.py
- polylogue/cli/arg_helpers.py
- polylogue/automation_targets.json
- polylogue/importers/claude_ai.py
- polylogue/importers/chatgpt.py
- tests/test_automation_snippets.py
- polylogue/cli/automation_cli.py
- polylogue/cli/context.py
- nix/modules/polylogue.nix
- polylogue/automation.py
| - Run `python3 polylogue.py --help` (or a specific subcommand) directly; every workflow is exposed via the CLI with skim/gum prompts only when needed. | ||
| - The first Drive action requests a Google OAuth client JSON and stores credentials/tokens under `$XDG_CONFIG_HOME/polylogue/`. | ||
| - Assume dependencies are always present: do **not** add graceful-degradation branches for missing CLI tools or libraries. Our NixOS devshell supplies gum, skim, rich, etc., so code should hard-require them. | ||
| - **Never add graceful-degradation fallbacks.** We run on NixOS and can guarantee every dependency; if a tool is missing it should be treated as a hard failure, not a best-effort path. | ||
|
|
||
| ## Automation & Testing | ||
| - Non-interactive paths use `--plain` to disable gum/skim/Rich; combine with `--json` for machine-readable summaries. | ||
| - Smoke test with `python3 polylogue.py render data --plain --dry-run` and `python3 polylogue.py sync --plain --dry-run`. | ||
| - Non-interactive paths automatically drop into a plain UI when stdout/stderr aren’t TTYs. Set `POLYLOGUE_FORCE_PLAIN=1` when you need deterministic plain mode in CI, or pass `--interactive` to re-enable gum/skim prompts even without a TTY. | ||
| - Smoke test with `POLYLOGUE_FORCE_PLAIN=1 python3 polylogue.py render data --dry-run` and `POLYLOGUE_FORCE_PLAIN=1 python3 polylogue.py sync --dry-run`. | ||
| - Run `pytest` regularly; new tests should live under `tests/`. | ||
| - Use `polylogue env` (with `--json` when needed) to confirm resolved config/output paths while debugging CI or support issues. |
There was a problem hiding this comment.
Restore the blank lines below these section headings.
## Development Workflow and ## Automation & Testing are immediately followed by list items, which trips markdownlint MD022 and can fail docs checks.
🧰 Tools
🪛 markdownlint-cli2 (0.22.0)
[warning] 16-16: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below
(MD022, blanks-around-headings)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@AGENTS.md` around lines 11 - 20, Add a blank line immediately after the
headings "## Development Workflow" and "## Automation & Testing" so each heading
is followed by an empty line before the subsequent list items (this addresses
markdownlint rule MD022 and prevents docs checks from failing); locate the two
headings in AGENTS.md and insert one newline between the heading line and the
first list item under each section.
| - `canonical` limits the output to `conversation.md` under each slug, skipping the branch tree entirely when you want a flat archive. | ||
|
|
||
| Because chat imports now travel through the same registrar/pipeline stack as sync/watch, the `--branch-export` flag behaves consistently everywhere (render, sync drive/codex/claude-code, and watchers). | ||
| `polylogue import chatgpt` (and downstream sync/watch flows) always write the canonical transcript alongside `conversation.common.md` and per-branch directories under `branches/<branch-id>/{<branch-id>.md, overlay.md}` so divergent replies stay organised without extra flags. |
There was a problem hiding this comment.
Remove the last stale layout wording in this section.
This paragraph documents the new fixed tree, but Line 40 still says the canonical transcript lives at <slug>.md, and the section heading still refers to “Modes”. As written, the page describes two different output layouts.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@docs/providers/chatgpt.md` at line 25, The docs still reference the old
layout: remove or update the stale wording that says the canonical transcript
lives at `<slug>.md` and rename the misleading section heading “Modes” to
reflect the fixed tree; instead document that `polylogue import chatgpt` always
writes the canonical transcript alongside `conversation.common.md` and
per-branch files under `branches/<branch-id>/{<branch-id>.md, overlay.md}` so
there is a single, consistent layout and no alternate `<slug>.md` placement.
| ### Branch Export Modes | ||
|
|
||
| Claude Code sessions respect the same `--branch-export full|overlay|canonical` flag as other providers. The default `full` layout mirrors the IDE’s branching history in `conversation.common.md` and `branches/<branch-id>/` directories. `overlay` trims the per-branch full copies, leaving just the overlays plus the canonical transcript, while `canonical` writes only `conversation.md` for a flatter archive. The flag applies to `polylogue import claude-code`, `polylogue sync claude-code`, and watchers because they share the registrar-backed pipeline. | ||
| Claude Code sessions always mirror the IDE’s branching history: `conversation.md` captures the canonical transcript, `conversation.common.md` stores shared context, and `branches/<branch-id>/{<branch-id>.md, overlay.md}` preserve each fork. Imports, syncs, and watchers share this layout because they run through the same registrar-backed pipeline. |
There was a problem hiding this comment.
Rename the outdated header to match the new fixed layout.
The section body now documents a single fixed layout, but the header still says “Branch Export Modes,” which implies configurable modes still exist.
✏️ Proposed doc fix
-### Branch Export Modes
+### Branch Layout🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@docs/providers/claude-code.md` around lines 24 - 26, Update the outdated
header "Branch Export Modes" to reflect the single fixed layout (e.g., "Branch
Export Layout" or "Branch Export (Fixed Layout)") and ensure any internal
references or cross-links use the new header text; keep the body as-is that
documents conversation.md, conversation.common.md, and
branches/<branch-id>/{<branch-id>.md, overlay.md} to match the header change.
| _polylogue_comp_file="$TMPDIR/polylogue-bash-completions" | ||
| python3 polylogue.py completions --shell bash >"$_polylogue_comp_file" 2>/dev/null || true | ||
| [ -f "$_polylogue_comp_file" ] && source "$_polylogue_comp_file" | ||
| elif [ -n "$ZSH_VERSION" ]; then | ||
| _polylogue_comp_file="$TMPDIR/polylogue-zsh-completions" | ||
| python3 polylogue.py completions --shell zsh >"$_polylogue_comp_file" 2>/dev/null || true | ||
| [ -f "$_polylogue_comp_file" ] && source "$_polylogue_comp_file" | ||
| elif [ -n "$FISH_VERSION" ]; then | ||
| _polylogue_comp_file="$TMPDIR/polylogue-fish-completions.fish" | ||
| python3 polylogue.py completions --shell fish >"$_polylogue_comp_file" 2>/dev/null || true | ||
| [ -f "$_polylogue_comp_file" ] && source "$_polylogue_comp_file" |
There was a problem hiding this comment.
Avoid sourcing predictable temp files in shell init.
Lines [46]-[56] use fixed temp filenames and source them even after suppressed generation errors. This can source stale/untrusted content and is brittle when TMPDIR is unset.
🔒 Safer pattern (unique temp file + success-gated source)
- if [ -n "$BASH_VERSION" ]; then
- _polylogue_comp_file="$TMPDIR/polylogue-bash-completions"
- python3 polylogue.py completions --shell bash >"$_polylogue_comp_file" 2>/dev/null || true
- [ -f "$_polylogue_comp_file" ] && source "$_polylogue_comp_file"
+ _polylogue_tmpdir="${TMPDIR:-/tmp}"
+ if [ -n "$BASH_VERSION" ]; then
+ _polylogue_comp_file="$(mktemp "${_polylogue_tmpdir%/}/polylogue-bash-completions.XXXXXX")"
+ if python3 polylogue.py completions --shell bash >"$_polylogue_comp_file" 2>/dev/null; then
+ source "$_polylogue_comp_file"
+ fi
elif [ -n "$ZSH_VERSION" ]; then
- _polylogue_comp_file="$TMPDIR/polylogue-zsh-completions"
- python3 polylogue.py completions --shell zsh >"$_polylogue_comp_file" 2>/dev/null || true
- [ -f "$_polylogue_comp_file" ] && source "$_polylogue_comp_file"
+ _polylogue_comp_file="$(mktemp "${_polylogue_tmpdir%/}/polylogue-zsh-completions.XXXXXX")"
+ if python3 polylogue.py completions --shell zsh >"$_polylogue_comp_file" 2>/dev/null; then
+ source "$_polylogue_comp_file"
+ fi
elif [ -n "$FISH_VERSION" ]; then
- _polylogue_comp_file="$TMPDIR/polylogue-fish-completions.fish"
- python3 polylogue.py completions --shell fish >"$_polylogue_comp_file" 2>/dev/null || true
- [ -f "$_polylogue_comp_file" ] && source "$_polylogue_comp_file"
+ _polylogue_comp_file="$(mktemp "${_polylogue_tmpdir%/}/polylogue-fish-completions.XXXXXX")"
+ if python3 polylogue.py completions --shell fish >"$_polylogue_comp_file" 2>/dev/null; then
+ source "$_polylogue_comp_file"
+ fi
fi🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@nix/devshell.nix` around lines 46 - 56, The current init uses predictable
temp filenames and blindly sources them even when generation may have failed;
change the logic around _polylogue_comp_file and the call to "python3
polylogue.py completions --shell ..." to create a unique temp file (e.g., via
mktemp or similar), ensure TMPDIR has a safe default if unset, run the
completions command and capture its exit status, and only source the temp file
when the command succeeded and the file exists; update the bash/zsh/fish blocks
that set _polylogue_comp_file and source it (and remove the "|| true"
suppressor) so stale or untrusted content cannot be sourced.
| i = 1 | ||
| while i < len(lines): | ||
| if lines[i].strip() == "---": | ||
| i += 1 | ||
| break | ||
| meta_lines.append(lines[i]) | ||
| i += 1 | ||
| body = "\n".join(lines[i:]) |
There was a problem hiding this comment.
Unclosed frontmatter block silently discards body content.
If the closing --- delimiter is missing, the entire content after the opening --- is parsed as metadata lines and body becomes an empty string. This could silently lose document content.
🛠️ Proposed fix to handle unclosed blocks
i = 1
+ found_close = False
while i < len(lines):
if lines[i].strip() == "---":
i += 1
+ found_close = True
break
meta_lines.append(lines[i])
i += 1
- body = "\n".join(lines[i:])
+ if found_close:
+ body = "\n".join(lines[i:])
+ else:
+ # No closing delimiter; treat entire text as body (no metadata)
+ return {}, text🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/_vendor/frontmatter.py` around lines 18 - 25, The frontmatter
parsing loop currently assumes a closing '---' was found and always sets body =
"\n".join(lines[i:]), which discards content when the delimiter is missing;
modify the loop to track whether the closing delimiter was found (e.g.,
found_close boolean set true inside the if block that breaks), and after the
loop if found_close is False reconstruct body from the collected meta_lines plus
remaining lines (e.g., body = "\n".join(meta_lines + lines[i:])) and clear
meta_lines, otherwise keep the existing behavior; refer to the variables
meta_lines, lines, body and the loop index i when making this change.
| ## What You Can Do | ||
| - **Render local logs:** Choose a file or directory; skim previews candidates, rich shows progress, and outputs land in the configured render directory (defaults to something like `~/polylogue-data/render`). Add `--html` for themed previews or `--diff` to see deltas when re-rendering. | ||
| - **Sync provider archives:** `polylogue sync drive|codex|claude-code|chatgpt|claude` unifies Drive pulls, local IDE sessions, and export bundles with consistent flags for collapse thresholds, HTML, pruning, diffs, and JSON output. Defaults from `polylogue.config` keep outputs in locations such as `~/polylogue-data/sync-drive`, `~/polylogue-data/codex`, `~/polylogue-data/claude-code`, `~/polylogue-data/chatgpt`, and `~/polylogue-data/claude`. ChatGPT/Claude exports are treated like local providers: drop ZIPs (or extracted directories containing `conversations.json`) under `$XDG_DATA_HOME/polylogue/exports/{chatgpt,claude}` and rerun `polylogue sync chatgpt` / `polylogue sync claude` as each export arrives. | ||
| - **Sync provider archives:** `polylogue sync drive|codex|claude-code|chatgpt|claude` unifies Drive pulls, local IDE sessions, and export bundles with consistent flags for collapse thresholds, HTML, pruning, diffs, and JSON output—now with Rich progress bars so you can see throughput as chats and sessions stream in. Defaults from `polylogue.config` keep outputs in locations such as `~/polylogue-data/sync-drive`, `~/polylogue-data/codex`, `~/polylogue-data/claude-code`, `~/polylogue-data/chatgpt`, and `~/polyologue-data/claude`. Drive runs accept explicit chat IDs via `--chat-id file-id --chat-id other-id`, while local providers can point at specific sessions via `--session path/to/session.jsonl` or skip pickers entirely with `--all`. ChatGPT/Claude exports are treated like local providers: drop ZIPs (or extracted directories containing `conversations.json`) under `$XDG_DATA_HOME/polylogue/exports/{chatgpt,claude}` and rerun `polylogue sync chatgpt` / `polylogue sync claude` as each export arrives. |
There was a problem hiding this comment.
Typo in output path.
"/polyologue-data/claude" should be "/polylogue-data/claude" (extra 'o' in polyologue).
📝 Fix typo
-Defaults from `polylogue.config` keep outputs in locations such as `~/polylogue-data/sync-drive`, `~/polylogue-data/codex`, `~/polylogue-data/claude-code`, `~/polylogue-data/chatgpt`, and `~/polyologue-data/claude`.
+Defaults from `polylogue.config` keep outputs in locations such as `~/polylogue-data/sync-drive`, `~/polylogue-data/codex`, `~/polylogue-data/claude-code`, `~/polylogue-data/chatgpt`, and `~/polylogue-data/claude`.📝 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.
| - **Sync provider archives:** `polylogue sync drive|codex|claude-code|chatgpt|claude` unifies Drive pulls, local IDE sessions, and export bundles with consistent flags for collapse thresholds, HTML, pruning, diffs, and JSON output—now with Rich progress bars so you can see throughput as chats and sessions stream in. Defaults from `polylogue.config` keep outputs in locations such as `~/polylogue-data/sync-drive`, `~/polylogue-data/codex`, `~/polylogue-data/claude-code`, `~/polylogue-data/chatgpt`, and `~/polyologue-data/claude`. Drive runs accept explicit chat IDs via `--chat-id file-id --chat-id other-id`, while local providers can point at specific sessions via `--session path/to/session.jsonl` or skip pickers entirely with `--all`. ChatGPT/Claude exports are treated like local providers: drop ZIPs (or extracted directories containing `conversations.json`) under `$XDG_DATA_HOME/polylogue/exports/{chatgpt,claude}` and rerun `polylogue sync chatgpt` / `polylogue sync claude` as each export arrives. | |
| - **Sync provider archives:** `polylogue sync drive|codex|claude-code|chatgpt|claude` unifies Drive pulls, local IDE sessions, and export bundles with consistent flags for collapse thresholds, HTML, pruning, diffs, and JSON output—now with Rich progress bars so you can see throughput as chats and sessions stream in. Defaults from `polylogue.config` keep outputs in locations such as `~/polylogue-data/sync-drive`, `~/polylogue-data/codex`, `~/polylogue-data/claude-code`, `~/polylogue-data/chatgpt`, and `~/polylogue-data/claude`. Drive runs accept explicit chat IDs via `--chat-id file-id --chat-id other-id`, while local providers can point at specific sessions via `--session path/to/session.jsonl` or skip pickers entirely with `--all`. ChatGPT/Claude exports are treated like local providers: drop ZIPs (or extracted directories containing `conversations.json`) under `$XDG_DATA_HOME/polylogue/exports/{chatgpt,claude}` and rerun `polylogue sync chatgpt` / `polylogue sync claude` as each export arrives. |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@README.md` at line 21, The README contains a typo in the default output path:
change any occurrence of "~/polyologue-data/claude" to the correct
"~/polylogue-data/claude" in the descriptive sentence under the "Sync provider
archives" section (the line that lists defaults and mentions `polylogue.config`
and paths such as `~/polylogue-data/sync-drive`, `~/polylogue-data/codex`,
etc.); ensure all similar misspellings of "polyologue" in that paragraph are
replaced with "polylogue" so paths and examples are consistent with the project
name and config.
| def test_help_lists_command_descriptions(): | ||
| ui = DummyUI() | ||
| env = CommandEnv(ui=ui) | ||
| run_help_cli(argparse.Namespace(), env) | ||
| joined = "\n".join(ui.console.lines) | ||
| assert "sync" in joined | ||
| assert "Synchronize provider archives" in joined |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Verify run_help_cli handles missing topic attribute.
argparse.Namespace() is passed without a topic attribute. If run_help_cli accesses args.topic directly without getattr or a default, this could raise AttributeError. The test passes, so presumably this is handled, but explicitly setting topic=None would make the intent clearer.
♻️ Make intent explicit
def test_help_lists_command_descriptions():
ui = DummyUI()
env = CommandEnv(ui=ui)
- run_help_cli(argparse.Namespace(), env)
+ run_help_cli(argparse.Namespace(topic=None), env)
joined = "\n".join(ui.console.lines)
assert "sync" in joined
assert "Synchronize provider archives" in joined🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@tests/test_cli_help_env.py` around lines 40 - 46, The test passes an
argparse.Namespace without an explicit topic which can be unclear; update
test_help_lists_command_descriptions to pass argparse.Namespace(topic=None) so
the intent that no topic is provided is explicit and to ensure run_help_cli is
exercised with a missing topic value (refer to run_help_cli and the
test_help_lists_command_descriptions/argparse.Namespace usage to locate the
change).
| notes = verify_sqlite_indexes(db_path) | ||
| assert any("messages_fts" in note for note in notes) |
There was a problem hiding this comment.
Assert the repair actually happened.
This still passes if verify_sqlite_indexes() only reports messages_fts as missing and never recreates it. Query sqlite_master after the call so the test proves the rebuild happened.
Proposed test tightening
notes = verify_sqlite_indexes(db_path)
assert any("messages_fts" in note for note in notes)
+ with sqlite3.connect(db_path) as conn:
+ rebuilt = conn.execute(
+ "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'messages_fts'"
+ ).fetchone()
+ assert rebuilt is not 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.
| notes = verify_sqlite_indexes(db_path) | |
| assert any("messages_fts" in note for note in notes) | |
| notes = verify_sqlite_indexes(db_path) | |
| assert any("messages_fts" in note for note in notes) | |
| with sqlite3.connect(db_path) as conn: | |
| rebuilt = conn.execute( | |
| "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'messages_fts'" | |
| ).fetchone() | |
| assert rebuilt is not None |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@tests/test_index_health.py` around lines 16 - 17, The test currently only
checks the returned notes from verify_sqlite_indexes(db_path) but not that the
FTS object was actually created; after calling verify_sqlite_indexes, open the
same SQLite database and query sqlite_master for an object named "messages_fts"
(e.g., SELECT name FROM sqlite_master WHERE name='messages_fts') and assert that
the query returns a row so the test proves the rebuild actually happened;
reference the existing verify_sqlite_indexes call and the "messages_fts" name
when adding the sqlite_master assertion.
| payload = capsys.readouterr().out.strip() | ||
| assert payload.startswith("{") and payload.endswith("}") | ||
| data = json.loads(payload) |
There was a problem hiding this comment.
json_lines test does not currently enforce single-line output.
Line [171] only checks object delimiters. Multi-line JSON would still pass, which weakens this regression test.
✅ Suggested test tightening
- payload = capsys.readouterr().out.strip()
- assert payload.startswith("{") and payload.endswith("}")
- data = json.loads(payload)
+ raw = capsys.readouterr().out
+ lines = [line for line in raw.splitlines() if line.strip()]
+ assert len(lines) == 1
+ data = json.loads(lines[0])🧰 Tools
🪛 Ruff (0.15.9)
[warning] 171-171: Assertion should be broken down into multiple parts
Break down assertion into multiple parts
(PT018)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@tests/test_status.py` around lines 170 - 172, The test currently only checks
that payload startswith "{" and endswith "}" (using payload and
json.loads(payload)), which allows multi-line JSON; update the assertion to
enforce single-line output by verifying the captured payload from
capsys.readouterr() contains no newline characters (e.g., assert "\n" not in
payload or payload.count("\n") == 0) or by comparing payload to a compact
serialization of the parsed object (json.dumps(data)); make this change around
the payload / data handling to ensure the JSON is a single line.
| def test_add_run_persists_metadata(tmp_path, monkeypatch): | ||
| _configure_state(monkeypatch, tmp_path) | ||
| monkeypatch.setenv("POLYLOGUE_RUN_LOG", "1") | ||
| util.add_run({"cmd": "render", "driveRetries": 2, "driveFailures": 1, "out": tmp_path / "out"}) | ||
| err = capsys.readouterr().err.strip() | ||
| assert err | ||
| payload = json.loads(err.splitlines()[-1]) | ||
| assert payload["event"] == "polylogue_run" | ||
| payload = util.load_runs(limit=1)[0] | ||
| assert payload["cmd"] == "render" | ||
| assert payload["retries"] == 2 | ||
| assert payload["failures"] == 1 | ||
| assert payload["driveRetries"] == 2 | ||
| assert payload["driveFailures"] == 1 |
There was a problem hiding this comment.
Assert the serialized out field here too.
out is the only non-primitive value in this payload, so it's the field most likely to regress during persistence. Right now this test still passes if add_run() drops or mangles it.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@tests/test_util_runs.py` around lines 20 - 26, The test
test_add_run_persists_metadata should also assert the serialized "out" value to
catch regressions: after calling util.add_run(...) and loading payload via
util.load_runs(...), add an assertion that payload["out"] equals the expected
serialized path (e.g., str(tmp_path / "out")) so the non-primitive field
persisted correctly; update the existing test_add_run_persists_metadata to
include this extra assertion referencing payload and util.add_run /
util.load_runs.
| entries: List[str] = [] | ||
| for cmd in commands: | ||
| desc = (descriptions or {}).get(cmd, "") | ||
| if desc: | ||
| desc_literal = desc.replace('"', '\\"') | ||
| entries.append(f'complete -c polylogue -f -a "{cmd}" -d "{desc_literal}"') | ||
| else: | ||
| entries.append(f'complete -c polylogue -f -a "{cmd}"') | ||
| entries = "\n".join(entries) | ||
| return entries.strip() |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Variable type changes from List[str] to str.
Line 201 reassigns entries from a list to a string, which is a code smell and can confuse readers and static analyzers.
♻️ Proposed fix
# fish
entries: List[str] = []
for cmd in commands:
desc = (descriptions or {}).get(cmd, "")
if desc:
desc_literal = desc.replace('"', '\\"')
entries.append(f'complete -c polylogue -f -a "{cmd}" -d "{desc_literal}"')
else:
entries.append(f'complete -c polylogue -f -a "{cmd}"')
- entries = "\n".join(entries)
- return entries.strip()
+ return "\n".join(entries)📝 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.
| entries: List[str] = [] | |
| for cmd in commands: | |
| desc = (descriptions or {}).get(cmd, "") | |
| if desc: | |
| desc_literal = desc.replace('"', '\\"') | |
| entries.append(f'complete -c polylogue -f -a "{cmd}" -d "{desc_literal}"') | |
| else: | |
| entries.append(f'complete -c polylogue -f -a "{cmd}"') | |
| entries = "\n".join(entries) | |
| return entries.strip() | |
| entries: List[str] = [] | |
| for cmd in commands: | |
| desc = (descriptions or {}).get(cmd, "") | |
| if desc: | |
| desc_literal = desc.replace('"', '\\"') | |
| entries.append(f'complete -c polylogue -f -a "{cmd}" -d "{desc_literal}"') | |
| else: | |
| entries.append(f'complete -c polylogue -f -a "{cmd}"') | |
| return "\n".join(entries) |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/cli/app.py` around lines 193 - 202, The code reassigns the variable
entries from a List[str] to a str (entries = "\n".join(entries)), which is
confusing; preserve the list type by keeping entries as List[str] and use a new
variable (e.g., entries_str or result) for the joined string, then return that
variable.strip(); update the function that builds completion lines (the entries
list construction block) to join into a new variable instead of mutating entries
so static analyzers and readers see consistent types for entries.
| def run_complete_cli(args: argparse.Namespace, env: Optional[CommandEnv] = None) -> None: | ||
| env = env or CommandEnv(ui=create_ui(True)) | ||
| engine = CompletionEngine(env, build_parser()) | ||
| completions = engine.complete(args.shell, args.cword, args.words or []) | ||
| for entry in completions: | ||
| if entry.description: | ||
| print(f"{entry.value}:{entry.description}") | ||
| else: | ||
| print(entry.value) |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Consider using keyword argument for clarity.
Line 280 passes True positionally to create_ui(). Using a keyword argument would improve readability.
♻️ Proposed fix
def run_complete_cli(args: argparse.Namespace, env: Optional[CommandEnv] = None) -> None:
- env = env or CommandEnv(ui=create_ui(True))
+ env = env or CommandEnv(ui=create_ui(plain=True))🧰 Tools
🪛 Ruff (0.15.9)
[warning] 280-280: Boolean positional value in function call
(FBT003)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/cli/app.py` around lines 279 - 287, The call create_ui(True) in
run_complete_cli is using a positional boolean which hurts readability; update
it to pass the boolean as a keyword argument using the actual parameter name
from create_ui's signature (e.g., if the parameter is named raw or enabled, call
create_ui(raw=True) or create_ui(enabled=True)), and keep the rest of the code
(CommandEnv(ui=...)) unchanged so intent is explicit.
| _ensure("runs", lambda args, env: run_runs_cli(args, env), "List recent runs") | ||
| _ensure("index", lambda args, env: run_index_cli(args, env), "Index maintenance helpers") |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Unnecessary lambdas.
These lambdas simply forward arguments without modification. The functions can be passed directly.
♻️ Proposed fix
- _ensure("runs", lambda args, env: run_runs_cli(args, env), "List recent runs")
- _ensure("index", lambda args, env: run_index_cli(args, env), "Index maintenance helpers")
+ _ensure("runs", run_runs_cli, "List recent runs")
+ _ensure("index", run_index_cli, "Index maintenance helpers")📝 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.
| _ensure("runs", lambda args, env: run_runs_cli(args, env), "List recent runs") | |
| _ensure("index", lambda args, env: run_index_cli(args, env), "Index maintenance helpers") | |
| _ensure("runs", run_runs_cli, "List recent runs") | |
| _ensure("index", run_index_cli, "Index maintenance helpers") |
🧰 Tools
🪛 Ruff (0.15.9)
[warning] 877-877: Lambda may be unnecessary; consider inlining inner function
Inline function call
(PLW0108)
[warning] 878-878: Lambda may be unnecessary; consider inlining inner function
Inline function call
(PLW0108)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/cli/app.py` around lines 877 - 878, The two lambda wrappers are
redundant; instead of _ensure("runs", lambda args, env: run_runs_cli(args, env),
...) and _ensure("index", lambda args, env: run_index_cli(args, env), ...), pass
the callables directly by using run_runs_cli and run_index_cli as the second
argument to _ensure (i.e., _ensure("runs", run_runs_cli, "List recent runs") and
_ensure("index", run_index_cli, "Index maintenance helpers")), ensuring the
function signatures of run_runs_cli and run_index_cli match the expected (args,
env) parameters.
| p_index = _add_command_parser(sub, "index", help="Index maintenance helpers", description="Inspect/repair Polylogue indexes") | ||
| index_sub = p_index.add_subparsers(dest="subcmd", required=True) | ||
| p_index_check = index_sub.add_parser("check", help="Validate SQLite/Qdrant indexes") | ||
| p_index_check.add_argument("--repair", action="store_true", help="Attempt to rebuild missing SQLite FTS data") | ||
| p_index_check.add_argument("--skip-qdrant", action="store_true", help="Skip Qdrant validation even when configured") | ||
| p_index_check.add_argument("--json", action="store_true", help="Emit validation results as JSON") |
There was a problem hiding this comment.
Inconsistent use of add_parser vs _add_command_parser.
Line 1085 uses index_sub.add_parser() directly while all other subparsers use _add_command_parser(), which sets the default formatter class. This inconsistency means the index check subparser won't have ArgumentDefaultsHelpFormatter.
🛠️ Proposed fix
p_index = _add_command_parser(sub, "index", help="Index maintenance helpers", description="Inspect/repair Polylogue indexes")
index_sub = p_index.add_subparsers(dest="subcmd", required=True)
- p_index_check = index_sub.add_parser("check", help="Validate SQLite/Qdrant indexes")
+ p_index_check = _add_command_parser(index_sub, "check", help="Validate SQLite/Qdrant indexes", description="Validate SQLite/Qdrant indexes")📝 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.
| p_index = _add_command_parser(sub, "index", help="Index maintenance helpers", description="Inspect/repair Polylogue indexes") | |
| index_sub = p_index.add_subparsers(dest="subcmd", required=True) | |
| p_index_check = index_sub.add_parser("check", help="Validate SQLite/Qdrant indexes") | |
| p_index_check.add_argument("--repair", action="store_true", help="Attempt to rebuild missing SQLite FTS data") | |
| p_index_check.add_argument("--skip-qdrant", action="store_true", help="Skip Qdrant validation even when configured") | |
| p_index_check.add_argument("--json", action="store_true", help="Emit validation results as JSON") | |
| p_index = _add_command_parser(sub, "index", help="Index maintenance helpers", description="Inspect/repair Polylogue indexes") | |
| index_sub = p_index.add_subparsers(dest="subcmd", required=True) | |
| p_index_check = _add_command_parser(index_sub, "check", help="Validate SQLite/Qdrant indexes", description="Validate SQLite/Qdrant indexes") | |
| p_index_check.add_argument("--repair", action="store_true", help="Attempt to rebuild missing SQLite FTS data") | |
| p_index_check.add_argument("--skip-qdrant", action="store_true", help="Skip Qdrant validation even when configured") | |
| p_index_check.add_argument("--json", action="store_true", help="Emit validation results as JSON") |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/cli/app.py` around lines 1083 - 1088, The p_index_check subparser
is created via index_sub.add_parser() instead of using the helper
_add_command_parser which applies the ArgumentDefaultsHelpFormatter; change the
creation of the "check" subcommand to call _add_command_parser(index_sub,
"check", help="Validate SQLite/Qdrant indexes") (and include the same
arguments/description) so that the p_index_check parser (used for adding
--repair, --skip-qdrant, --json) gets the same formatter behavior as other
subparsers.
Replace the interactive menu with a CLI-first command surface, add shell completions, Rich dashboards, and substantially expand doctor diagnostics. Auto-detect plain mode from TTY state instead of requiring an explicit --plain flag. New commands: - `completions --shell bash|zsh|fish` emits sourcing scripts; zsh variant calls back into `polylogue _complete` for live suggestions (slugs, provider names, Drive chat IDs, session paths) - `dashboards` renders Rich provider-summary and recent-runs tables (or `--json` for machine consumption) - `runs` lists run history with `--providers`, `--commands`, `--since`/`--until` filters and Rich/plain/JSON output - `env` prints resolved config path, output directories, state/runs DB locations, and watchable providers (`--json` for scripts) - `help [COMMAND]` shows per-command argparse help plus a command listing table - `index check` validates SQLite FTS integrity and optionally Qdrant reachability, with `--repair` to rebuild missing tables CLI surface changes: - Remove `--plain` flag; plain mode auto-activates when stdout/stderr are not TTYs or `POLYLOGUE_FORCE_PLAIN=1` is set; `--interactive` re-enables prompts in headless shells - Remove `--branch-export` flag; branch layout is always full (canonical + common + per-branch directories) - Delete the interactive menu, settings menu, and all prompt_* functions from app.py (~400 lines); bare `polylogue` now prints help instead of launching a menu - Remove `automation` command, automation.py, automation_targets.json, and the NixOS module (nix/modules/polylogue.nix) - Remove structured stderr run logging (POLYLOGUE_RUN_LOG env var) - Add `--json-lines` to `status` for newline-delimited streaming Doctor enhancements (polylogue/doctor.py): - Check PATH for required CLI tools (gum, sk, bat, glow, delta) with hints pointing to `nix develop` - Verify config file presence with candidate-path hints - Check Drive credentials.json and token.json with OAuth hints - Run SQLite integrity + FTS table checks via index_health module - Probe Qdrant collection reachability when backend is configured - Issues now carry a `hint` field; Rich table output uses severity coloring Progress and retry UX: - Rich progress bars wrap Drive sync and local-sync session loops - Drive retry callback prints yellow retry/delay messages to console - Import/sync summaries include "Previous run" footer from util helpers (latest_run, format_run_brief) Infrastructure: - polylogue/providers/ package with ProviderRegistry protocol and DriveProviderSession wrapper around DriveClient - polylogue/_vendor/ fallbacks for frontmatter, pyperclip, and watchfiles when external packages are absent - polylogue/core/config_validation.py validates config at startup via Pydantic (rejects bad themes, non-numeric thresholds, unknown keys) - CompletionEngine (cli/completion_engine.py) resolves live completions from registrar state, argparse metadata, and provider session listings - nix/devshell.nix auto-sources the completion script for the active shell on entry Packaging: - Remove automation_targets.json from package-data in pyproject.toml - Delete flake.nix nixosModules export
|
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
Rework the CLI from an interactive-menu-first tool into a command-first surface with proper shell completions, richer diagnostics, and automatic plain-mode detection. Along the way, retire the automation snippet generator and NixOS module, simplify branch export to always-full, and add several new subcommands for operational visibility.
Motivation
The interactive menu was the original entry point, but in practice every workflow was already reachable via
polylogue <command>. The menu added ~400 lines of prompt/handler code that duplicated the argument parsing, and it made the tool harder to script—you had to remember--plainfor every non-interactive invocation. Meanwhile, shell completions were missing entirely, so tab-completing provider names or slugs required memorization or--help.The
--branch-export full|overlay|canonicalflag added cognitive load without much practical value: almost every user wantedfull, and theoverlay/canonicalmodes were undertested edge cases. Dropping them simplifies every importer, the render path, and the sync flow.The automation module (
polylogue automation systemd|cron) and NixOS module were speculative infrastructure—useful in theory but not battle-tested and carrying a maintenance cost (the NixOS module alone was 226 lines of Nix). Removing them now lets us focus on the CLI ergonomics that actually get used daily.Changes by concern
Shell completions
The
completions --shell bash|zsh|fishcommand emits a sourcing script. Bash and fish get staticcompgen/completescripts. Zsh gets a dynamic completion function that calls back intopolylogue _complete --shell zsh --cword N -- words…, which routes throughCompletionEngine:The devshell hook (
nix/devshell.nix) auto-generates and sources the script for bash, zsh, or fish onnix developentry.Automatic plain-mode detection
--plainis replaced by TTY detection in_should_use_plain():--interactiveoverrides the detection for headless shells where you still want gum/skim prompts. TheInteractiveConsoleFacadenow raisesRuntimeError(caught asSystemExit) when required tools are missing, without silently falling back—since the devshell guarantees them, a missing tool means you're outside the shell and should know about it.New commands: dashboards, runs, env, help, index check
dashboardsrenders Rich tables of provider health (runs/items/attachments/failures) and the last N runs.--jsonemits the same data as JSON.runsis the filtered run-history viewer—--providers,--commands,--since/--until,--json.envdumps resolved configuration: config path, collapse threshold, HTML settings, all output directories, state DB path, runs DB path, watchable providers.help [COMMAND]prints the command's argparse help, or a command-listing table when no topic is given.index checkrunsverify_sqlite_indexes()(integrity check + FTS table presence) and optionallyverify_qdrant_collection().--repairrebuilds missing FTS tables.Doctor enhancements
Doctor runs five additional check categories:
qdrantEvery
DoctorIssuecarries an optionalhintstring, and the Rich table output uses severity-colored rows.Config validation at startup
polylogue/core/config_validation.pydefines Pydantic models (ConfigModel,DefaultsModel,OutputDirsModel) withextra = "forbid". The config is validated on load, so typos likehtml_theme: "purple"orcollapse_threshold: "fast"produce an actionableSystemExitinstead of silent misbehavior.Progress bars and retry UX
Drive sync and local-sync loops wrap their iteration in
ui.progress(), which renders a Rich progress bar (spinner + bar + count + elapsed + remaining) in interactive mode and is a no-op in plain mode. The Drive retry path accepts anotifiercallback that prints yellow retry messages to the console.Removed: automation, NixOS module, branch-export, interactive menu, structured run logs
automation.py+automation_targets.jsonnix/modules/polylogue.nixcli/automation_cli.py--branch-exportflagPOLYLOGUE_RUN_LOGstderr emissionProvider registry
New
polylogue/providers/package introducesProviderSessionprotocol,ProviderRegistry, andDriveProviderSession(wrapsDriveClientwith__getattr__delegation).CommandEnvholds aProviderRegistryand adrive_constructorfactory, and_ensure_drive()registers the session so downstream code can look up providers by name.Vendor fallbacks
polylogue/_vendor/provides minimal fallback implementations forfrontmatter,pyperclip, andwatchfilesso the import paths are always valid. Thefrontmattervendor is a ~65-line YAML front-matter parser;pyperclipis an in-memory stub;watchfilesraisesRuntimeErroron call (explicit failure instead of silent no-op).Testing
test_cli_help_env.py,test_dashboards.py,test_runs_cli.py,test_index_cli.py,test_index_health.py,test_config_validation.pytest_cli_flags.py(Drive sync selection, local sync sessions),test_status.py(json-lines),test_util_runs.py(latest_run, format_run_brief),test_watch_cli.py(error surfacing)test_automation_snippets.py, branch-export-mode tests fromtest_branch_and_search.pyandtest_render_branch.py