Repository navigation
Conversation
📝 WalkthroughWalkthroughThe PR renames the project from "Gemini Markdown (gmd)" to "Polylogue," updates all environment variables (GMD_* → POLYLOGUE_*), migrates configuration and state storage to XDG-compliant directories, adds provider-specific output defaults, and updates associated documentation, modules, and tests accordingly. Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 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 |
Rebrand the package from its Gemini-specific origin (chatmd/gmd) to polylogue, reflecting multi-provider scope. Restructure the module layout, adopt XDG base directories, and assign per-provider output defaults. Package and entrypoint: - Rename chatmd/ to polylogue/, gmd.py to polylogue/cli.py - Add thin polylogue.py launcher that delegates to polylogue.cli.main() - Move gmd_config.py and gmd_settings.py into the polylogue package as polylogue/config.py and polylogue/settings.py - Delete the old TOML-based chatmd/config.py (.gmdrc loader) XDG base directory adoption: - Credentials and tokens now live under $XDG_CONFIG_HOME/polylogue/ (default ~/.config/polylogue/) instead of project-root flat files - Run state (state.json, runs.json) moves to $XDG_STATE_HOME/polylogue/ - All write paths call mkdir(parents=True, exist_ok=True) before first use - Environment variables renamed: GMD_* → POLYLOGUE_* (RETRIES, RETRY_BASE, AUTH_MODE, TOKEN_PATH, NO_COLOR, CONFIG) Per-provider output directories: - OutputDirs dataclass gains import_chatgpt and import_claude fields - Defaults point to /realm/data/chatlog/markdown/<provider> hierarchy - Import subcommands (chatgpt, claude, claude-code, codex) now resolve to their own provider-specific output dirs instead of all falling back to the render directory - CLI help strings surface the actual defaults per subcommand Provider path corrections: - Claude Code DEFAULT_PROJECT_ROOT: ~/.config/claude/projects → ~/.claude/projects - DriveClient credential prompt references polylogue.py instead of gmd.py Documentation and tests: - README.md, AGENTS.md, multi-provider.md updated for new binary name, package paths, XDG locations, and per-provider output table - All test imports rewritten from chatmd.* to polylogue.*
There was a problem hiding this comment.
Actionable comments posted: 4
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
polylogue/cli.py (1)
1111-1142:⚠️ Potential issue | 🔴 Critical
diff_enabledis undefined—this will raise aNameErrorat runtime.In
run_sync_claude_code(), line 1140 referencesdiff_enabled, but unlikerun_sync_codex()(which defines it at line 1037), this function never assigns it. This will crash whensync-claude-codeis invoked.🐛 Proposed fix
force = args.force prune = args.prune + diff_enabled = getattr(args, "diff", False) selected_paths: Optional[List[Path]] = NoneAdd after line 1119.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@polylogue/cli.py` around lines 1111 - 1142, The function run_sync_claude_code references diff_enabled when calling sync_claude_code_sessions but never defines it; add a definition for diff_enabled (mirroring run_sync_codex) e.g. set diff_enabled = args.diff or SETTINGS.diff_previews before calling sync_claude_code_sessions so the variable exists and matches the CLI/setting behavior expected by sync_claude_code_sessions.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@polylogue/config.py`:
- Around line 17-28: ARCHIVE_ROOT is hardcoded; change it to respect
XDG_DATA_HOME (falling back to ~/.local/share) and then derive MARKDOWN_ROOT and
the OutputDirs defaults from that; specifically, compute ARCHIVE_ROOT by reading
os.environ.get("XDG_DATA_HOME") and using
Path(XDG_DATA_HOME)/"realm"/"data"/"chatlog" else
Path.home()/".local"/"share"/"realm"/"data"/"chatlog", keep MARKDOWN_ROOT =
ARCHIVE_ROOT / "markdown" and leave the OutputDirs fields (render, sync_drive,
sync_codex, sync_claude_code, import_chatgpt, import_claude) unchanged so they
continue to derive from MARKDOWN_ROOT.
In `@polylogue/drive.py`:
- Around line 24-33: The _retry function currently swallows all exceptions while
parsing POLYLOGUE_RETRIES and POLYLOGUE_RETRY_BASE which can mask bugs; change
the except clauses to only catch parsing-related errors (ValueError and
TypeError) when converting to int/float so only invalid env values are ignored
and other errors bubble up; keep the same fallback behavior and references to
the POLYLOGUE_RETRIES and POLYLOGUE_RETRY_BASE environment variables and the
_retry function name to locate the changes.
- Around line 51-53: The POLYLOGUE_TOKEN_PATH value from the environment isn't
having ~ expanded, so token_path may point to a non-existent location; update
the token_path assignment to expand the user's home (e.g., use
os.path.expanduser or Path(os.path.expanduser(token_env))) when token_env is set
before constructing token_path (the code referencing token_env, token_path,
POLYLOGUE_TOKEN_PATH, credentials_path and TOKEN_FILE should be adjusted
accordingly) so subsequent exists(), mkdir(), and open() calls work with
expanded paths.
In `@polylogue/util.py`:
- Line 10: The import and type hints use typing.Dict which is unnecessary on
Python 3.9+; update the import line by removing Dict from typing and replace all
occurrences of Dict[str, Any] in this module (e.g., type hints in functions or
variables referencing Dict) with the built-in generic form dict[str, Any],
keeping Any and Optional as needed and adjusting the from typing import ... list
accordingly (remove Dict from the import list and use dict[str, Any] in places
like function signatures and variable annotations).
---
Outside diff comments:
In `@polylogue/cli.py`:
- Around line 1111-1142: The function run_sync_claude_code references
diff_enabled when calling sync_claude_code_sessions but never defines it; add a
definition for diff_enabled (mirroring run_sync_codex) e.g. set diff_enabled =
args.diff or SETTINGS.diff_previews before calling sync_claude_code_sessions so
the variable exists and matches the CLI/setting behavior expected by
sync_claude_code_sessions.
🪄 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: 1bfb2dbf-707b-43fa-bd76-533dc11d515b
📒 Files selected for processing (33)
AGENTS.mdREADME.mdchatmd/config.pynix/devshell.nixpolylogue/__init__.pypolylogue/cli.pypolylogue/cli_common.pypolylogue/commands.pypolylogue/config.pypolylogue/doctor.pypolylogue/drive.pypolylogue/drive_client.pypolylogue/html.pypolylogue/importers/__init__.pypolylogue/importers/base.pypolylogue/importers/chatgpt.pypolylogue/importers/claude_ai.pypolylogue/importers/claude_code.pypolylogue/importers/codex.pypolylogue/importers/utils.pypolylogue/local_sync.pypolylogue/models.pypolylogue/options.pypolylogue/render.pypolylogue/settings.pypolylogue/ui.pypolylogue/util.pytests/test_codex_importer.pytests/test_doctor.pytests/test_html.pytests/test_importers_multi.pytests/test_local_sync.pytests/test_stats.py
💤 Files with no reviewable changes (1)
- chatmd/config.py
| ARCHIVE_ROOT = Path("/realm/data/chatlog") | ||
| MARKDOWN_ROOT = ARCHIVE_ROOT / "markdown" | ||
|
|
||
|
|
||
| @dataclass | ||
| class OutputDirs: | ||
| render: Path = Path("gmd_out") | ||
| sync_drive: Path = Path("gemini_synced") | ||
| sync_codex: Path = Path("codex_synced") | ||
| sync_claude_code: Path = Path("claude_code_synced") | ||
| render: Path = MARKDOWN_ROOT / "gemini-render" | ||
| sync_drive: Path = MARKDOWN_ROOT / "gemini-sync" | ||
| sync_codex: Path = MARKDOWN_ROOT / "codex" | ||
| sync_claude_code: Path = MARKDOWN_ROOT / "claude-code" | ||
| import_chatgpt: Path = MARKDOWN_ROOT / "chatgpt" | ||
| import_claude: Path = MARKDOWN_ROOT / "claude" |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Check if /realm/data/chatlog is documented or mentioned elsewhere
rg -n '/realm/data' --type=md
rg -n 'ARCHIVE_ROOT|MARKDOWN_ROOT' --type=pyRepository: Sinity/polylogue
Length of output: 2201
🏁 Script executed:
#!/bin/bash
# Check for config file handling and CLI argument override mechanism
rg -n 'config|Config' polylogue/config.py -A 3 -B 1 | head -40
# Check how OutputDirs is instantiated and used
rg -n 'OutputDirs' --type=py -A 2 -B 1
# Look for CLI argument handling for output paths
rg -n 'argparse|click|--out' --type=py | head -20
# Check if there are any environment variable usages
rg -n 'environ|getenv|XDG' --type=pyRepository: Sinity/polylogue
Length of output: 3922
🏁 Script executed:
#!/bin/bash
# Check how output_dirs is used in the codebase and if defaults are relied upon
rg -n 'output_dirs\|OutputDirs' --type=py -B 2 -A 4
# Check if ARCHIVE_ROOT is used directly elsewhere
rg -n 'ARCHIVE_ROOT' --type=py
# Check config.json defaults or examples
fd -e 'json|example' | xargs grep -l 'output_dirs' 2>/dev/null || echo "No example configs found"Repository: Sinity/polylogue
Length of output: 215
Consider using XDG standards for default paths to align with platform conventions.
The ARCHIVE_ROOT default uses an absolute hardcoded path. While users can override this via config.json or the --out CLI argument, the default could be more portable. The codebase already follows XDG conventions for config (XDG_CONFIG_HOME) and state (XDG_STATE_HOME) paths elsewhere—applying the same pattern here would provide consistency.
💡 Alternative default using XDG_DATA_HOME
-ARCHIVE_ROOT = Path("/realm/data/chatlog")
-MARKDOWN_ROOT = ARCHIVE_ROOT / "markdown"
+DATA_HOME = Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local/share"))
+ARCHIVE_ROOT = DATA_HOME / "polylogue" / "chatlog"
+MARKDOWN_ROOT = ARCHIVE_ROOT / "markdown"🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/config.py` around lines 17 - 28, ARCHIVE_ROOT is hardcoded; change
it to respect XDG_DATA_HOME (falling back to ~/.local/share) and then derive
MARKDOWN_ROOT and the OutputDirs defaults from that; specifically, compute
ARCHIVE_ROOT by reading os.environ.get("XDG_DATA_HOME") and using
Path(XDG_DATA_HOME)/"realm"/"data"/"chatlog" else
Path.home()/".local"/"share"/"realm"/"data"/"chatlog", keep MARKDOWN_ROOT =
ARCHIVE_ROOT / "markdown" and leave the OutputDirs fields (render, sync_drive,
sync_codex, sync_claude_code, import_chatgpt, import_claude) unchanged so they
continue to derive from MARKDOWN_ROOT.
| def _retry(fn, *, retries: int = 3, base_delay: float = 0.5): | ||
| # Allow env overrides for tuning | ||
| try: | ||
| retries = int(os.environ.get("GMD_RETRIES", retries)) | ||
| retries = int(os.environ.get("POLYLOGUE_RETRIES", retries)) | ||
| except Exception: | ||
| pass | ||
| try: | ||
| base_delay = float(os.environ.get("GMD_RETRY_BASE", base_delay)) | ||
| base_delay = float(os.environ.get("POLYLOGUE_RETRY_BASE", base_delay)) | ||
| except Exception: | ||
| pass |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Narrow exception handling for retry env parsing.
Catching Exception here can mask unintended failures; only parse errors should be swallowed.
Proposed refactor
def _retry(fn, *, retries: int = 3, base_delay: float = 0.5):
# Allow env overrides for tuning
try:
retries = int(os.environ.get("POLYLOGUE_RETRIES", retries))
- except Exception:
+ except (TypeError, ValueError):
pass
try:
base_delay = float(os.environ.get("POLYLOGUE_RETRY_BASE", base_delay))
- except Exception:
+ except (TypeError, ValueError):
pass🧰 Tools
🪛 Ruff (0.15.9)
[warning] 24-24: Missing return type annotation for private function _retry
(ANN202)
[warning] 26-29: Use contextlib.suppress(Exception) instead of try-except-pass
Replace try-except-pass with with contextlib.suppress(Exception): ...
(SIM105)
[error] 28-29: try-except-pass detected, consider logging the exception
(S110)
[warning] 28-28: Do not catch blind exception: Exception
(BLE001)
[warning] 30-33: Use contextlib.suppress(Exception) instead of try-except-pass
Replace try-except-pass with with contextlib.suppress(Exception): ...
(SIM105)
[error] 32-33: try-except-pass detected, consider logging the exception
(S110)
[warning] 32-32: Do not catch blind exception: Exception
(BLE001)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/drive.py` around lines 24 - 33, The _retry function currently
swallows all exceptions while parsing POLYLOGUE_RETRIES and POLYLOGUE_RETRY_BASE
which can mask bugs; change the except clauses to only catch parsing-related
errors (ValueError and TypeError) when converting to int/float so only invalid
env values are ignored and other errors bubble up; keep the same fallback
behavior and references to the POLYLOGUE_RETRIES and POLYLOGUE_RETRY_BASE
environment variables and the _retry function name to locate the changes.
| token_env = os.environ.get("POLYLOGUE_TOKEN_PATH") | ||
| token_path = Path(token_env) if token_env else (credentials_path.parent / TOKEN_FILE) | ||
| if token_path.exists(): |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
# First, let's find and examine the file
find . -name "drive.py" -type f | head -20Repository: Sinity/polylogue
Length of output: 80
🏁 Script executed:
# Let's also check the structure of the repository
ls -laRepository: Sinity/polylogue
Length of output: 1132
🏁 Script executed:
# Read the polylogue/drive.py file to see the actual code
cat -n polylogue/drive.py | head -80Repository: Sinity/polylogue
Length of output: 3387
🏁 Script executed:
# Check if there are tests for the token path handling
find tests -name "*.py" -type f | xargs ls -laRepository: Sinity/polylogue
Length of output: 571
🏁 Script executed:
# Check if there are any tests for the drive module
grep -r "drive\|token_path\|POLYLOGUE_TOKEN_PATH" tests/ --include="*.py"Repository: Sinity/polylogue
Length of output: 42
🏁 Script executed:
# Let's verify the Path behavior with tilde expansion
python3 << 'EOF'
from pathlib import Path
# Test 1: Path with tilde (without expanduser)
test_path_str = "~/.config/polylogue/token.json"
path_without_expand = Path(test_path_str)
print(f"Path('{test_path_str}'): {path_without_expand}")
print(f"String representation: {str(path_without_expand)}")
print(f"Exists (will be False with literal ~): {path_without_expand.exists()}")
# Test 2: Path with expanduser()
path_with_expand = Path(test_path_str).expanduser()
print(f"\nPath('{test_path_str}').expanduser(): {path_with_expand}")
print(f"String representation: {str(path_with_expand)}")
print(f"Exists: {path_with_expand.exists()}")
# Test 3: Show the difference in string representation
print(f"\nDifference in strings:")
print(f"Without expand: {str(path_without_expand)}")
print(f"With expand: {str(path_with_expand)}")
EOFRepository: Sinity/polylogue
Length of output: 536
🏁 Script executed:
# Check if expanduser() is used elsewhere in the codebase
rg "expanduser" --type pyRepository: Sinity/polylogue
Length of output: 1058
🏁 Script executed:
# Check the full function to understand context better
cat -n polylogue/drive.py | sed -n '46,85p'Repository: Sinity/polylogue
Length of output: 2047
Expand ~ in POLYLOGUE_TOKEN_PATH environment variable.
When users set POLYLOGUE_TOKEN_PATH=~/.config/..., the ~ is not expanded and causes the file lookup to fail. This breaks both the exists() check and subsequent file operations like mkdir() and open().
Proposed fix
- token_path = Path(token_env) if token_env else (credentials_path.parent / TOKEN_FILE)
+ token_path = Path(token_env).expanduser() if token_env else (credentials_path.parent / TOKEN_FILE)This follows the pattern consistently used throughout the codebase (local_sync.py, config.py, cli.py, etc.) for expanding environment variable paths.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/drive.py` around lines 51 - 53, The POLYLOGUE_TOKEN_PATH value from
the environment isn't having ~ expanded, so token_path may point to a
non-existent location; update the token_path assignment to expand the user's
home (e.g., use os.path.expanduser or Path(os.path.expanduser(token_env))) when
token_env is set before constructing token_path (the code referencing token_env,
token_path, POLYLOGUE_TOKEN_PATH, credentials_path and TOKEN_FILE should be
adjusted accordingly) so subsequent exists(), mkdir(), and open() calls work
with expanded paths.
| import tempfile | ||
| from pathlib import Path | ||
| from typing import Optional, Any, Dict | ||
| from typing import Any, Dict, Optional |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Consider using built-in dict instead of typing.Dict.
As of Python 3.9+, dict can be used directly in type hints, making typing.Dict unnecessary.
🧹 Proposed fix
-from typing import Any, Dict, Optional
+from typing import Any, OptionalThen replace Dict[str, Any] with dict[str, Any] throughout the file.
🧰 Tools
🪛 Ruff (0.15.9)
[warning] 10-10: typing.Dict is deprecated, use dict instead
(UP035)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/util.py` at line 10, The import and type hints use typing.Dict
which is unnecessary on Python 3.9+; update the import line by removing Dict
from typing and replace all occurrences of Dict[str, Any] in this module (e.g.,
type hints in functions or variables referencing Dict) with the built-in generic
form dict[str, Any], keeping Any and Optional as needed and adjusting the from
typing import ... list accordingly (remove Dict from the import list and use
dict[str, Any] in places like function signatures and variable annotations).
There was a problem hiding this comment.
Pull request overview
This PR completes a broad rebrand/refactor from the earlier Gemini-centric naming to Polylogue, while also moving configuration and runtime state to XDG-compliant locations and updating default output roots to be provider-specific.
Changes:
- Renames CLI/package surfaces (
chatmd→polylogue,gmd.py→polylogue/cli.py+polylogue.pylauncher) and updates docs/tests accordingly. - Migrates config/state handling to XDG paths and updates env var prefixes to
POLYLOGUE_*. - Introduces/updates multi-provider importers (ChatGPT, Claude, Claude Code, Codex), HTML rendering, and provider-specific output directory defaults.
Reviewed changes
Copilot reviewed 16 out of 33 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| tests/test_stats.py | Updates imports to polylogue.* and new CLI entrypoint. |
| tests/test_local_sync.py | Updates local sync imports to the renamed package. |
| tests/test_importers_multi.py | Updates importer imports to polylogue.importers.*. |
| tests/test_html.py | Updates HTML transform import to new module path. |
| tests/test_doctor.py | Updates doctor import to new module path. |
| tests/test_codex_importer.py | Updates Codex importer import to new module path. |
| README.md | Rebrands documentation and updates usage/config/token path guidance. |
| polylogue/util.py | Moves cached state/runs paths to XDG state home; updates no-color env var name. |
| polylogue/ui.py | Adds a UI abstraction for plain vs gum/rich interaction and TTY detection. |
| polylogue/settings.py | Introduces global settings container and reset helper. |
| polylogue/render.py | Adds Markdown document model + render helpers and attachment metadata handling. |
| polylogue/options.py | Introduces typed option/result dataclasses for commands. |
| polylogue/models.py | Adds Pydantic-based validation/normalization for Gemini chunks. |
| polylogue/local_sync.py | Adds sync logic for local Codex/Claude Code session stores. |
| polylogue/importers/utils.py | Adds token estimation and large-text spill-to-attachment helpers. |
| polylogue/importers/codex.py | Adds Codex JSONL importer and attachment extraction for large chunks. |
| polylogue/importers/claude_code.py | Updates Claude Code default project root to ~/.claude/projects. |
| polylogue/importers/claude_ai.py | Adds Claude export importer/listing and attachment copying logic. |
| polylogue/importers/chatgpt.py | Adds ChatGPT export importer/listing and attachment handling. |
| polylogue/importers/base.py | Introduces ImportResult shared return type. |
| polylogue/importers/init.py | Exposes importer entrypoints from the package. |
| polylogue/html.py | Adds HTML preview renderer and callout transformation. |
| polylogue/drive.py | Updates env var tuning to POLYLOGUE_* and ensures token dir exists before writes. |
| polylogue/drive_client.py | Moves default credentials/token paths under XDG config dir; updates prompts. |
| polylogue/doctor.py | Adds doctor inspections for Codex/Claude Code JSONL validity. |
| polylogue/config.py | Introduces JSON config loader under XDG config dir and new provider-specific output defaults. |
| polylogue/commands.py | Refactors core render/sync/list/status command implementations into a package module. |
| polylogue/cli.py | Updates CLI wiring, defaults, help text, and import subcommands for Polylogue. |
| polylogue/cli_common.py | Adds shared CLI utilities (skim selection, pruning computation, filtering). |
| polylogue/init.py | Adds package export list. |
| nix/devshell.nix | Updates comments to reflect Polylogue naming. |
| chatmd/config.py | Deletes legacy TOML-based .gmdrc config loader. |
| AGENTS.md | Updates repo guidelines/docs to the new name and XDG storage locations. |
Comments suppressed due to low confidence (3)
polylogue/drive_client.py:46
- The plain-mode error message tells users to place
credentials.jsonnext topolylogue.py, butDriveClientactually reads/writes credentials under the XDG config dir (DEFAULT_CREDENTIALS). Updating this message to point at the real expected path (and/or mention$XDG_CONFIG_HOME/polylogue/credentials.json) will avoid confusing non-interactive/CI users.
polylogue/config.py:21 - The default archive root is hard-coded to
/realm/data/chatlog, so first-run commands will try to create directories under/realm/...by default. On most systems this path won't exist or won't be user-writable, causing failures unless the user provides a config override. Consider defaulting to a user-writable location (e.g.,$XDG_DATA_HOME/$XDG_STATE_HOME, or a relative output directory) and optionally allowing an env var to set the archive root.
polylogue/cli.py:804 sample_configpoints at../docs/polylogue.config.sample.jsonc, but this repository currently has nodocs/directory (and the path will also be invalid when installed as a package). Consider shipping the sample config as package data (loaded viaimportlib.resources) or only showing this hint when the file exists.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| - Copy `docs/config.sample.jsonc` as a starting point to set default collapse thresholds, HTML preferences, and output directories once. | ||
| - `gmd doctor` reports the expected locations when no config is detected. | ||
| - Polylogue reads configuration from `$POLYLOGUE_CONFIG`, `$XDG_CONFIG_HOME/polylogue/config.json`, or (legacy) `~/.polylogueconfig`. | ||
| - Copy `docs/polylogue.config.sample.jsonc` to `$XDG_CONFIG_HOME/polylogue/config.json` to customise collapse thresholds, HTML defaults, and per-provider output directories. |
There was a problem hiding this comment.
README references docs/polylogue.config.sample.jsonc, but there is no docs/ directory in this branch (so the path is currently broken). Either add the sample config file at that location or update the README to point at an existing sample config path.
| - Copy `docs/polylogue.config.sample.jsonc` to `$XDG_CONFIG_HOME/polylogue/config.json` to customise collapse thresholds, HTML defaults, and per-provider output directories. | |
| - Create `$XDG_CONFIG_HOME/polylogue/config.json` (or point `$POLYLOGUE_CONFIG` at your file) to customise collapse thresholds, HTML defaults, and per-provider output directories. |
Rebrand the package from its Gemini-specific origin (chatmd/gmd) to polylogue, reflecting multi-provider scope. Restructure the module layout, adopt XDG base directories, and assign per-provider output defaults. Package and entrypoint: - Rename chatmd/ to polylogue/, gmd.py to polylogue/cli.py - Add thin polylogue.py launcher that delegates to polylogue.cli.main() - Move gmd_config.py and gmd_settings.py into the polylogue package as polylogue/config.py and polylogue/settings.py - Delete the old TOML-based chatmd/config.py (.gmdrc loader) XDG base directory adoption: - Credentials and tokens now live under $XDG_CONFIG_HOME/polylogue/ (default ~/.config/polylogue/) instead of project-root flat files - Run state (state.json, runs.json) moves to $XDG_STATE_HOME/polylogue/ - All write paths call mkdir(parents=True, exist_ok=True) before first use - Environment variables renamed: GMD_* → POLYLOGUE_* (RETRIES, RETRY_BASE, AUTH_MODE, TOKEN_PATH, NO_COLOR, CONFIG) Per-provider output directories: - OutputDirs dataclass gains import_chatgpt and import_claude fields - Defaults point to /realm/data/chatlog/markdown/<provider> hierarchy - Import subcommands (chatgpt, claude, claude-code, codex) now resolve to their own provider-specific output dirs instead of all falling back to the render directory - CLI help strings surface the actual defaults per subcommand Provider path corrections: - Claude Code DEFAULT_PROJECT_ROOT: ~/.config/claude/projects → ~/.claude/projects - DriveClient credential prompt references polylogue.py instead of gmd.py Documentation and tests: - README.md, AGENTS.md, multi-provider.md updated for new binary name, package paths, XDG locations, and per-provider output table - All test imports rewritten from chatmd.* to polylogue.*
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6163360f04
ℹ️ 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".
Findings addressed: - #5: SIGKILL test uses min_count=N_SESSIONS*MESSAGES//2 not 1, so kill lands during active ingestion. - #6: VmRSS replaced with VmPeak (high-water mark) so the memory assertion measures peak rather than post-cleanup RSS. - #7: _wait_for_daemon_ready uses proc.poll() instead of os.kill(pid, 0), avoiding PID-reuse TOCTOU. SIGKILL via raw PID is kept where proc.poll() guards it. - #8: _has_systemd_scope() memoised to avoid repeated fork+exec at module-load / collection time. - #9: Dead assert snap1["session_profiles"] >= 0 replaced with explicit == 0 assertion documenting daemon-only materialization. - #10: _parse_code_records (private API) replaced with parse_payload("claude-code", ...) in test_provider_contracts and test_corpus_edge_cases. - #11: test_concurrent_access_safety docstring updated to document that --no-api mode tests WAL read-during-write, not daemon API concurrency. - #12: _write_corpus_files dead return value removed; callers iterate corpus_dir directly. - #13: topology-target.yaml regenerated via build-topology-projection. - #14: Stale verification_reports domain entry removed from test-coverage-domains.yaml (all referenced files deleted). Co-Authored-By: Claude Opus 4.7 <[email protected]>
#3318) ## Summary Addresses the 8 CodeRabbit findings on PR #3076 (daemon-coordinated online index rebuilds) that were left unaddressed at merge time, tracked as polylogue-ogn1. Each finding was independently re-verified against current source before any fix was applied — several turned out to already be resolved by the time this bead was filed. ## Problem polylogue-ogn1 notes: "CodeRabbit's review on the PR (commit 667ad8e, before the final rebase) flagged 8 actionable findings that were not addressed before merge because the merging task was scoped specifically to a conflict-free rebase onto origin/master, not a full code-review pass." ## Disposition matrix (finding -> status, evidence) | # | Finding | Disposition | Evidence | |---|---|---|---| | 1 | HTTP handler must reject `max_blob_mb` without `raw_ids`/`only_missing` before promoting | **Already resolved** | `validate_rebuild_index_request` already enforced this in the originally merged commit `1c2a07f9b` (`git show 1c2a07f:polylogue/maintenance/rebuild_index.py`), called first thing inside `rebuild_index_from_source` and again explicitly in the HTTP handler before dispatch. No change needed. | | 2/5 | Bridge's fixed ~30s `run_sync` timeout vs. the 600s CLI/HTTP rebuild contract | **Fixed** | Added `DaemonWriteThreadBridge.run_sync_with_timeout` (per-call override); `run_sync` now delegates to it with the bridge's own default so every other caller is unaffected. The rebuild-index HTTP route calls it with `_REBUILD_INDEX_WRITE_TIMEOUT_S = 600.0`, matching the CLI's own `urlopen(..., timeout=600)`. | | 3 | CLI `--daemon-url` default read `POLYLOGUE_DAEMON_URL` directly, bypassing the 5-layer config chain | **Fixed** | `_rebuild_index.py` now has its own `_default_daemon_url()` resolving via `load_polylogue_config().daemon_url`, matching `status.py`'s established pattern. | | 4 | HTTP handler fell back to running the rebuild directly when `write_bridge` was missing, instead of failing closed | **Fixed** | A real `DaemonAPIHTTPServer` always installs `write_bridge` in `__init__` (confirmed by reading the constructor), so this branch was unreachable in production — but a route that *can* execute an authority-promoting write outside the sole-writer coordinator is a bypass of the daemon's single-writer invariant, not a safe fallback. Now returns `503 write_coordinator_unavailable`. | | 6 | `missing_index_raw_ids` returned `[]` whenever `index.db` didn't exist yet | **Fixed** | Now falls back to the full source set (`all_index_rebuild_raw_ids`) when the index tier is absent — a fresh/lost index has nothing indexed, so every source row is missing by definition. Previously `--only-missing` silently rebuilt nothing on a fresh archive or right after `ops reset --index`. | | 7 | Partial-selection-cannot-promote validation only enforced by the CLI, not the shared service | **Already resolved** | Same evidence as #1 — `validate_rebuild_index_request` is called as the first statement inside the shared `rebuild_index_from_source`, so every caller (CLI, HTTP) goes through it. | | 8 | `rebuild_index.py` (substrate) imported the CLI's private `_archive_readiness_status`, inverting the repo's layering rule | **Fixed** | Extracted the readiness-surface computation into `polylogue/storage/archive_readiness.py` (`archive_readiness_status` + its `_archive_readiness_counts`/`_action_readiness_counts`/`_archive_status_surfaces` helpers); `status.py` now delegates to the same shared implementation instead of owning the only copy. | | 9 | Daemon-driven execution could promote from an empty source snapshot (`raw_count == 0`), unlike the CLI's own early exit | **Already resolved** | Same evidence as #1/#7 — the `raw_count == 0` short-circuit lives inside `rebuild_index_from_source` itself, before any replay, executed by every caller. | | 10 | `test_rebuild_index_route_uses_the_bridge_run_sync_writer_path` replaced `_handle_rebuild_index` wholesale, proving only its own stand-in | **Fixed** | Rewritten (renamed to `test_rebuild_index_route_uses_the_bridge_run_sync_with_timeout_writer_path`) to drive the real `_do_post_impl` dispatch and the real `_handle_rebuild_index` implementation end to end, with only the typed rebuild service itself stubbed. | ## Solution - `polylogue/daemon/write_coordinator.py` — new `run_sync_with_timeout`. - `polylogue/daemon/http.py` — fail-closed on missing write bridge; 600s timeout constant for the rebuild-index route. - `polylogue/cli/commands/maintenance/_rebuild_index.py` — config-resolved daemon URL default. - `polylogue/maintenance/rebuild_index.py` — `missing_index_raw_ids` fresh-index fix; import switched to the extracted shared readiness module. - `polylogue/storage/archive_readiness.py` — new `archive_readiness_status` (+ helpers), the layering fix for #8. - `polylogue/cli/commands/status.py` — delegates to the shared module instead of owning the readiness computation. - Tests: `tests/unit/daemon/test_maintenance_endpoints.py` (fail-closed proof), `tests/unit/daemon/test_write_coordinator.py` (real timeout-override proof), `tests/unit/maintenance/test_rebuild_index_selection.py` (new, fresh-index selection + shared-service validation), `tests/unit/daemon/test_http_write_coordination.py` (real-dispatch rewrite), `tests/unit/cli/commands/test_status.py` (import fixup for the moved functions). ## Verification - `mypy polylogue` (strict): `Success: no issues found in 1082 source files` - `ruff check .` / `ruff format --check .`: all checks passed / all formatted - `devtools verify --quick`: `exit_code: 0` (includes `degrade-loudly`, now allowlisted with rationale for the two extracted typed-signal except-handlers in `docs/plans/degrade-loudly-allowlist.yaml`) - `devtools render all --check`: no `out of sync` lines, exit 0 - `devtools test` across the affected area (status/rebuild_index/daemon http/ write_coordinator/maintenance CLI, 8 files): 264 passed, 1 pre-existing unrelated failure (`test_archive_facade_route_catalog_covers_public_async_facade`, confirmed failing identically on `origin/master` via `git stash` before this change — a facade/hook-event route catalog completeness check unrelated to rebuild-index) Ref polylogue-ogn1 Co-Authored-By: Claude <[email protected]> Co-authored-by: Claude <[email protected]>
|
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. |
Strengthens a batch of weak daemon and query tests. Product behaviour is unchanged. Each nomination was checked against the code first. Changed: the panic answer test compares the documented text (fixed prefix and suffix, the injected panic's message between); lifecycle tests compare each rejected service input with its exact message, read back the accepted write's stored request, match the worker-exit output by whole line and rename the watchdog-budget probe test to what it checks; the measure test binds the quota answer; the feed tests count event lines, check the final position against the reader's position and check the order of the two archive peers by ref; the page test compares the continuation's row values in full and now exercises the read context (a reader ahead opens the cursor, a reader behind in either counter or on another index file gets stale_cursor, per the shared cursor binding); query tests pin the `chrono` search to exactly sessions #2 and #8, search punctuation with a query whose answer is known (three prompts), pin the quoted-misspelling answer as empty, pin the four ambiguity candidates, give the fused paging loop a page cap and a non-empty answer, pin the physical error-call id sets, require the attached list to be present, and count projected and kept event rows. The until-instant test is renamed for the rule it pins (a seconds-precision bound covers its whole second). The duplicate abandoned-branch test in generated.rs is deleted; unknowns.rs covers it. Not changed, with reasons: refusal wording in the feed envelope test and the saved-relation diagnostics (the wording is owned by the shared command-surface and query-language crates); the exists-matches and kept-matches counts (whether the logical session's rows include its continuation's error call could not be settled by reading); the unit list in the closed-set message (other units may also accept `error`); the injection test's upper bound (an exact oracle per payload needs a run to confirm); the hang-up helper's bounded poll (the cancellation has no waiter to block on; a comment says so). Verified: by reading only (the host could not build), formatted with rustfmt. The hosted check is the verification. Some new exact expectations (candidate set, quoted-misspelling empty, physical total of 8, null session key, the stale_cursor code) come from reading the code and fixtures; a CI failure on one of them is a finding to settle, not an assertion to loosen. Task: none 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01UuFixtGtdh2xCEcLPgpRtf Co-authored-by: Claude Sonnet 5.5 <[email protected]>
…arding tests (#7236) Strengthens nine weak assertions in the Python client integration test, the deadline e2e tests and the onboarding tour test. Expected values come from the fixtures and the Morrow oracle, not from running the code. - Python client: the sessions query compares the three fixture session ids; the clean read must be outcome `ok`; the archive-alias test compares the full argv, which also covers the `status` subcommand that no other test exercises. - Deadline e2e: the refusal message is compared exactly (the CLI prints the daemon's failure verbatim). The deadline-0 import now reads the session back through the daemon (`sessions` shows exactly `chatgpt:deadline-import`, and `read` returns the text "synthetic import"), which the import report alone did not prove. - Onboarding e2e: the first query compares row sessions with the oracle's first column (#2, #8) instead of the count; the note step checks the stored note text; the takeover pointer line is compared whole, including the listing command; the preparation figure is checked as positive and against the transcript header. The loop asserting every step text is non-empty is deleted: it cannot tell a placeholder from rendered text, and the transcript comparison shares its source. Decisions: the note row's kind is not asserted because the default projection of annotation rows was not confirmed by reading; the value is. Exact rendered text of tour steps was not pinned since it cannot be known without running. Verified: by reading only (no local build, the host is short of memory), plus the hosted check. Behaviour is unchanged; if a stronger assertion fails on CI it is a finding, not something to loosen. Task: walk2 tests-1 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01UuFixtGtdh2xCEcLPgpRtf Co-authored-by: Claude Sonnet 5.5 <[email protected]>
Summary
I renamed the project from its Gemini-era naming to
polylogue, moved the main entrypoint topolylogue/cli.pywith a thinpolylogue.pylauncher, and shifted config/state handling onto XDG-compliant paths. I used the rename as a chance to fix the remaining layout mismatches: environment variables use thePOLYLOGUE_*prefix, provider outputs no longer fall back to one generic render directory, and docs/tests read like a multi-provider archive tool instead of a renamed Gemini utility. Most of the diff is mechanical package movement, but the behavioral effect is important for unattended use because credentials, tokens, run logs, and state no longer depend on the project root. This is the branch where the name, on-disk layout, and default paths finally match what the tool has become.Motivation
By this point the tool was no longer honestly described by
gmdorchatmd. It can import multiple providers, sync local session stores, generate stats, and validate archives. Keeping Gemini-shaped naming around would make every later feature harder to explain and every public interface slightly misleading. The rename is not cosmetic; it is the point where the code, docs, and runtime paths stop telling users they are working with a single-provider Gemini tool.The XDG move belongs in the same branch. Once we are talking about a multi-provider archival tool, storing credentials, tokens, and runtime state in ad hoc project-root locations becomes increasingly awkward, especially for automation. XDG config/state dirs are a better fit for long-lived auth material, JSON state, and run logs, and they line up with the config story from the previous branch much better than the older
.gmdrc/ flat-file leftovers did.Wanted to fix the output-root semantics while the rename was already touching CLI help and docs. Provider imports should not all default to the generic render directory; a multi-provider archive reads much more cleanly when ChatGPT, Claude, Claude Code, Codex, and Gemini each have their own archive root.
Changes by concern
1. Rename the package and entrypoint surfaces
The mechanical part is simple but wide-reaching:
chatmd/becomespolylogue/gmd.pybecomespolylogue/cli.pypolylogue.pyforwards intopolylogue.cli.main()Kept the thin launcher because it preserves the simple “run the repo directly” workflow while still putting the real CLI implementation inside the package.
On the config/settings side, I moved
gmd_config.pyandgmd_settings.pyinto the package aspolylogue/config.pyandpolylogue/settings.py. That removes the odd split where package code depended on top-level modules that looked more like app leftovers than library code.2. XDG-compliant credentials, tokens, and state
The more important behavior change is path handling. Credentials and tokens resolve under
$XDG_CONFIG_HOME/polylogue/and runtime state (state.json,runs.json) moves under$XDG_STATE_HOME/polylogue/. The code creates parent directories before first write so:can appear lazily on first use without special install steps.
Renamed the env var surface from
GMD_*toPOLYLOGUE_*, which affects retry tuning, auth mode, token path, no-color behavior, and config resolution. That is a deliberate compatibility break, but it keeps the public surface consistent with the new identity.3. Provider-specific defaults and path correction
OutputDirsgains provider-specific roots so imports no longer all default to the render directory. Instead, the CLI help now shows defaults like/realm/data/chatlog/markdown/chatgptor/realm/data/chatlog/markdown/claudedirectly on the relevant subcommands. That makes the archive layout visible and predictable at the point of use.Corrected Claude Code’s
DEFAULT_PROJECT_ROOTfrom~/.config/claude/projectsto~/.claude/projects. This is a small diff but a material usability fix: the importer/sync commands should target the path that the tool actually uses.4. Documentation and test rewrite
Because the rename is user-facing, I updated
README.md,AGENTS.md, andmulti-provider.mdin the same branch. The docs now describepolylogue.py, XDG config/state locations, provider-specific output roots, and the updated command names. Rewrote test imports fromchatmd.*topolylogue.*so the suite keeps tracking the real package name rather than a transition alias.Testing
The existing pytest suite still runs after the rename, and the main test-side change here is namespace churn: test imports now target
polylogue.*throughout. This branch does not add new behavior-specific tests for XDG migration or provider default output directories, so those pieces are primarily validated through manual CLI/doc checks.Notes
.gmdrcloader rather than trying to keep two config stories alive under the new name.