Repository navigation
Conversation
This reverts commit ae36a0aa234e95a4d6574a0bc7872a2886ccc4d3.
📝 WalkthroughWalkthroughThis pull request introduces a multi-provider conversation import ecosystem with local sync, validation, and analytics. It renames the package from Changes
Sequence DiagramssequenceDiagram
participant User
participant CLI as gmd.py CLI
participant Importer as Provider Importer
participant Renderer as Markdown/HTML Renderer
participant Filesystem
User->>CLI: import chatgpt/claude/codex/claude-code
CLI->>Importer: Load & parse export (ZIP/dir/JSONL)
Importer->>Importer: Normalize roles, extract content
Importer->>Importer: Resolve & copy attachments
Importer->>Renderer: Build MarkdownDocument with chunks
Renderer->>Renderer: Estimate tokens, compute stats
Renderer->>Filesystem: Write .md file
alt HTML enabled
Renderer->>Renderer: Render to HTML with callouts→details
Renderer->>Filesystem: Write .html file
end
Importer->>Filesystem: Copy/remove attachments dir
Importer->>CLI: Return ImportResult
CLI->>User: Output summary (paths, counts)
sequenceDiagram
participant User
participant CLI as gmd.py CLI
participant Sync as Local Sync
participant Importer as Session Importer
participant Storage as Output Directory
User->>CLI: sync-codex / sync-claude-code
CLI->>Sync: Call sync function with base_dir, force, prune
Sync->>Sync: Discover .jsonl session files
loop For each session
alt Skip if up-to-date and not forced
Sync->>Sync: Check file mtime
else Import
alt Diff enabled
Sync->>Storage: snapshot_for_diff
end
Sync->>Importer: import_*_session
Importer->>Storage: Write .md (+ .html if enabled)
alt Diff enabled
Sync->>Storage: write_delta_diff
end
Sync->>Sync: Accumulate metrics (attachments, tokens, diffs)
end
end
alt Prune enabled
Sync->>Storage: Compute stale outputs
Sync->>Storage: Delete pruned paths
end
Sync->>CLI: Return LocalSyncResult
CLI->>User: Report written/skipped/pruned/metrics
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes The PR introduces substantial new functionality across importers, local sync, doctor validation, and CLI integration with diverse patterns (multi-format parsing, attachment handling, file system operations, diff generation). While individual importer implementations follow similar templates, the heterogeneity of changes (new modules, control flow in commands, configuration loading, HTML transformations) and density of logic in sync/import orchestration demand careful reasoning across multiple files. 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 |
Rename the geminimd package to chatmd and introduce an importer subsystem that converts ChatGPT, Claude.ai, Claude Code, and Codex exports into the same Markdown pipeline used for Gemini Drive sync. Importer subsystem (chatmd/importers/): - base.py defines ImportResult; utils.py provides token estimation (tiktoken when available, word-count fallback) and store_large_text() to spill oversized chunks into _attachments/ with inline previews - chatgpt.py parses conversations.json from ZIP or directory, walks the mapping DAG to order messages, copies referenced files from the export's files/ directory, and normalises tool_calls/tool_result parts - claude_ai.py handles the Anthropic bundle format, renders tool_use / tool_result content blocks as paired call/result chunks, and indexes attachments from attachments/, files/, and assets/ directories - claude_code.py reads session JSONL, stitches tool_use/tool_result by ID, extracts summaries into front-matter, and records workspace + session path provenance - codex.py validates entries via Pydantic, pairs function_call / function_call_output by call_id, and filters out environment preamble Local sync (chatmd/local_sync.py): - sync_codex_sessions() and sync_claude_code_sessions() mirror local session stores with mtime-based skip, prune of stale outputs, and optional delta diff generation via write_delta_diff() - Diff tracking uses snapshot_for_diff() to capture pre-render state and produces unified diffs (delta when available, difflib fallback) CLI surface (gmd.py): - New subcommands: import chatgpt/claude/claude-code/codex, sync-codex, sync-claude-code, doctor, stats - Import commands offer interactive skim pickers or --all/--conversation-id for batch mode; sync commands add --force/--prune/--diff flags - stats command reads front-matter from output directories with optional --since/--until date filtering and per-provider breakdowns - summarize_import() renders Rich tables when available Configuration (gmd_config.py): - JSON config loaded from $GMD_CONFIG, XDG_CONFIG_HOME/gmd/config.json, or ~/.gmdconfig with defaults for collapse threshold, HTML preferences, and per-command output directories Supporting changes: - doctor.py validates JSONL integrity for Codex and Claude Code sessions - html.py adds collapsible callout support via _transform_callouts(), converting [!KIND]+/- blockquotes to interactive details elements - render.py tracks attachmentCount and attachmentBytes in metadata - util.py gains snapshot_for_diff(), write_delta_diff(), and timestamps in add_run() records; status_command aggregates run_summary stats - options.py adds diff field to RenderOptions/SyncOptions/RenderFile/SyncItem - flake.nix adds checks.default for pytest; .envrc enables direnv Tests: - test_codex_importer.py: tool attachment extraction, empty dir cleanup - test_importers_multi.py: ChatGPT/Claude/Claude Code basic import, tool call pairing, ZIP-with-attachment round-trips - test_local_sync.py: Codex and Claude Code sync, skip, prune - test_doctor.py: invalid JSONL detection - test_html.py: callout transformation, plain blockquote passthrough - test_stats.py: JSON output with date filtering
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8e87f22fae
ℹ️ 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.
Pull request overview
Expands the project from a Gemini-only renderer into a multi-provider conversation archive tool (chatmd) by adding provider-specific importers, local session sync for CLI tools, and new CLI subcommands (import/sync/doctor/stats), while keeping the existing chunk-based Markdown pipeline as the normalization target.
Changes:
- Added importers for ChatGPT exports, Claude.ai exports, Claude Code sessions, and Codex sessions, all normalizing to the shared chunk pipeline (attachments + token estimation + stats).
- Added local sync layer for Codex/Claude Code JSONL directories with mtime-based skipping, optional pruning, and optional diff output.
- Added doctor/stats CLI commands plus HTML callout folding improvements and a JSON-based config loader.
Reviewed changes
Copilot reviewed 27 out of 35 changed files in this pull request and generated 11 comments.
Show a summary per file
| File | Description |
|---|---|
| tests/test_stats.py | Adds coverage for gmd stats JSON output and date filtering. |
| tests/test_local_sync.py | Adds end-to-end coverage for local sync skip/prune behavior. |
| tests/test_importers_multi.py | Adds cross-provider importer smoke tests, tool pairing, and ZIP attachment round-trips. |
| tests/test_html.py | Adds tests for HTML callout-to-<details> transformation. |
| tests/test_doctor.py | Adds coverage for doctor detecting invalid JSONL sessions. |
| tests/test_codex_importer.py | Adds coverage for Codex tool output spill-to-attachment and empty attachment cleanup. |
| tests/conftest.py | Ensures repo root is on sys.path for tests. |
| README.md | Updates docs for new providers, commands, config, and behavior. |
| gmd.py | Renames imports to chatmd, adds new subcommands (import/sync/doctor/stats), config defaults, and richer summaries. |
| gmd_config.py | Adds JSON config loading with default paths and env override. |
| flake.nix | Adds a Nix checks.default that runs pytest with required Python deps. |
| chatmd/util.py | Adds run timestamps and diff helpers (snapshot_for_diff, write_delta_diff). |
| chatmd/ui.py | Introduces a UI abstraction supporting gum-based interactive and plain modes. |
| chatmd/render.py | Adds attachment count/bytes into stats and frontmatter metadata. |
| chatmd/options.py | Extends render/sync options and results to include diff and adds status run summary field. |
| chatmd/models.py | Adds Pydantic validation/normalization for chunk payloads. |
| chatmd/local_sync.py | Adds local sync implementation for Codex and Claude Code sessions. |
| chatmd/importers/utils.py | Adds token estimation + large-text spilling helper shared by importers. |
| chatmd/importers/codex.py | Adds Codex JSONL importer with tool call/output merging and large output extraction. |
| chatmd/importers/claude_code.py | Adds Claude Code JSONL importer with summary handling and tool pairing. |
| chatmd/importers/claude_ai.py | Adds Claude.ai ZIP/directory importer with typed blocks + attachments indexing. |
| chatmd/importers/chatgpt.py | Adds ChatGPT export importer including mapping traversal and attachment copying. |
| chatmd/importers/base.py | Introduces ImportResult shared return type for importers/sync. |
| chatmd/importers/init.py | Exposes importer entry points for CLI usage. |
| chatmd/html.py | Adds callout folding transform to HTML render output + supporting CSS. |
| chatmd/drive.py | Adds Drive helper functions with retry logic and optional auth modes. |
| chatmd/drive_client.py | Adds a Drive client wrapper integrating credentials flow with UI. |
| chatmd/doctor.py | Adds validation helpers for local session directories and JSONL sanity checks. |
| chatmd/config.py | Adds a TOML .gmdrc config loader (currently unused by CLI). |
| chatmd/commands.py | Adds diff support to render/sync, richer run logging, and status run summaries. |
| chatmd/cli_common.py | Adds skim selection, pruning helper, and shared filtering utilities. |
| chatmd/init.py | Exposes top-level chatmd package symbols. |
| AGENTS.md | Updates module path documentation from geminimd/ to chatmd/. |
| .gitignore | Ignores .direnv/ and sinex_md/ outputs. |
| .envrc | Enables direnv to use the Nix flake devshell. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| @@ -8,22 +8,103 @@ | |||
| from pathlib import Path | |||
| from typing import List, Optional | |||
There was a problem hiding this comment.
run_stats_cli() uses Dict/Any type hints but this module only imports List/Optional from typing, which will raise NameError when defining _load_metadata and the totals/per-provider dicts. Import Any and Dict (or switch to dict/object annotations) at the top of the file.
| from typing import List, Optional | |
| from typing import Any, Dict, List, Optional |
| def run_sync_claude_code(args: argparse.Namespace, env: CommandEnv) -> None: | ||
| ui = env.ui | ||
| base_dir = Path(args.base_dir) if args.base_dir else DEFAULT_PROJECT_ROOT | ||
| out_dir = Path(args.out) if args.out else DEFAULT_CLAUDE_CODE_SYNC_OUT | ||
| collapse = args.collapse_threshold or DEFAULT_COLLAPSE | ||
| html_enabled = args.html or SETTINGS.html_previews | ||
| html_theme = args.html_theme or SETTINGS.html_theme | ||
| force = args.force | ||
| prune = args.prune | ||
|
|
||
| selected_paths: Optional[List[Path]] = None | ||
| if not args.all and not ui.plain: | ||
| session_entries = list_claude_code_sessions(base_dir) | ||
| sessions = [Path(entry["path"]) for entry in session_entries] | ||
| selection = _collect_session_selection(ui, sessions, "Select Claude Code sessions") | ||
| if selection is None: | ||
| return | ||
| if not selection: | ||
| return | ||
| selected_paths = selection | ||
|
|
||
| result = sync_claude_code_sessions( | ||
| base_dir=base_dir, | ||
| output_dir=out_dir, | ||
| collapse_threshold=collapse, | ||
| html=html_enabled, | ||
| html_theme=html_theme, | ||
| force=force, | ||
| prune=prune, | ||
| diff=diff_enabled, | ||
| sessions=selected_paths, | ||
| ) |
There was a problem hiding this comment.
run_sync_claude_code() passes diff=diff_enabled, but diff_enabled is never defined in this function (unlike run_sync_codex()), so this will raise NameError at runtime. Define diff_enabled = getattr(args, "diff", False) (or similar) before calling sync_claude_code_sessions().
| sample_config = Path(__file__).resolve().parent / "docs" / "config.sample.jsonc" | ||
| config_hint = { | ||
| "cmd": "doctor", | ||
| "checked": {k: int(v) for k, v in report.checked.items()}, | ||
| "issues": [ | ||
| { | ||
| "provider": issue.provider, | ||
| "path": str(issue.path), | ||
| "message": issue.message, | ||
| "severity": issue.severity, | ||
| } | ||
| for issue in report.issues | ||
| ], | ||
| "configPath": str(CONFIG_PATH) if CONFIG_PATH else None, | ||
| "configEnv": CONFIG_ENV, | ||
| "configCandidates": [str(p) for p in DEFAULT_PATHS], | ||
| "configSample": str(sample_config), | ||
| } |
There was a problem hiding this comment.
sample_config points to .../docs/config.sample.jsonc, but there is no docs/ directory in the repo, so this hint will reference a non-existent file. Either add the sample config file to the repository or update the path/message to match the actual location/format of the config template.
| def _load_export(path: Path) -> Tuple[Path, Optional[TemporaryDirectory]]: | ||
| if path.is_dir(): | ||
| return path, None | ||
| if path.suffix.lower() != ".zip": | ||
| raise FileNotFoundError(f"Unsupported ChatGPT export: {path}") | ||
| tmp = TemporaryDirectory(prefix="chatgpt-export-") | ||
| with zipfile.ZipFile(path) as zf: | ||
| zf.extractall(tmp.name) | ||
| return Path(tmp.name), tmp |
There was a problem hiding this comment.
Using ZipFile.extractall() on untrusted ZIPs allows Zip Slip (path traversal via ../ entries). Validate each member path stays within the temporary directory (or extract members manually with a safe join) before writing files to disk.
| def _load_bundle(path: Path) -> Tuple[Path, Optional[TemporaryDirectory]]: | ||
| if path.is_dir(): | ||
| return path, None | ||
| if path.suffix.lower() != ".zip": | ||
| raise FileNotFoundError(f"Unsupported Claude export: {path}") | ||
| tmp = TemporaryDirectory(prefix="claude-export-") | ||
| with zipfile.ZipFile(path) as zf: | ||
| zf.extractall(tmp.name) | ||
| return Path(tmp.name), tmp |
There was a problem hiding this comment.
Using ZipFile.extractall() on untrusted ZIPs allows Zip Slip (path traversal via ../ entries). Validate each member path stays within the temporary directory (or extract members manually with a safe join) before writing files to disk.
| return None | ||
| attachments_dir.mkdir(parents=True, exist_ok=True) | ||
| target = attachments_dir / name | ||
| counter = 1 | ||
| while target.exists(): | ||
| target = attachments_dir / f"{target.stem}_{counter}{target.suffix}" | ||
| counter += 1 | ||
| target.write_bytes(source.read_bytes()) | ||
| try: |
There was a problem hiding this comment.
Attachment filenames from the export (name) are used directly in attachments_dir / name. If name contains path separators (e.g., ../), this can write outside the attachments directory. Sanitize to a basename (and ideally run through sanitize_filename) and reject absolute/parent-traversal paths before writing.
| entry = json.loads(raw) | ||
| try: |
There was a problem hiding this comment.
The JSONL read loop calls json.loads(raw) without handling JSONDecodeError, so a blank/partial/corrupted line will crash the import. Wrap the json.loads in try/except json.JSONDecodeError (and continue) to make imports and sync more robust.
| entry = json.loads(raw) | |
| try: | |
| try: | |
| entry = json.loads(raw) | |
| except json.JSONDecodeError: | |
| continue | |
| try: |
| return "assistant" | ||
| if role in {"user", "assistant", "tool", "system"}: | ||
| if role == "assistant": | ||
| return "model" | ||
| return role | ||
| if role == "function": | ||
| return "tool" | ||
| return "assistant" |
There was a problem hiding this comment.
_normalise_role() returns "assistant" when role is missing/unknown. Downstream stats in build_markdown_from_chunks() count model turns/tokens only when role == "model", so this undercounts. Consider defaulting unknown/missing roles to "model" (and returning "model" for unknown values).
| return "assistant" | |
| if role in {"user", "assistant", "tool", "system"}: | |
| if role == "assistant": | |
| return "model" | |
| return role | |
| if role == "function": | |
| return "tool" | |
| return "assistant" | |
| return "model" | |
| if role in {"user", "assistant", "tool", "system"}: | |
| if role == "assistant": | |
| return "model" | |
| return role | |
| if role == "function": | |
| return "tool" | |
| return "model" |
| elif ptype == "function_call": | ||
| name = payload.name or "tool" | ||
| args = payload.arguments or "{}" | ||
| if not isinstance(args, str): | ||
| args = json.dumps(args, indent=2, ensure_ascii=False) | ||
| chunk_text = f"Tool call `{name}`\n```json\n{args}\n```" | ||
| chunks.append( | ||
| { | ||
| "role": "model", | ||
| "text": chunk_text, | ||
| "tokenCount": estimate_token_count(chunk_text, model="gpt-5-codex"), | ||
| } | ||
| ) | ||
| call_index[payload.call_id or ""] = len(chunks) - 1 | ||
|
|
||
| elif ptype == "function_call_output": | ||
| output_text = payload.output or "" | ||
| call_id = payload.call_id or "" | ||
| idx = call_index.get(call_id) | ||
| if idx is not None: | ||
| chunks[idx]["text"] += f"\n\nOutput:\n{output_text}" | ||
| chunks[idx]["tokenCount"] = estimate_token_count(chunks[idx]["text"], model="gpt-5-codex") | ||
| else: | ||
| chunks.append( |
There was a problem hiding this comment.
When payload.call_id is missing, this stores the index under an empty-string key (""), which will be overwritten by subsequent tool calls and can cause unrelated function_call_output entries (also missing call_id) to be merged into the wrong chunk. Only index calls when call_id is truthy, and treat missing IDs as unpaired outputs.
| elif etype == "tool_use": | ||
| name = entry.get("name") or entry.get("toolName") or "tool" | ||
| input_payload = entry.get("input") or entry.get("args") or {} | ||
| text = f"Tool call `{name}`\n```json\n{json.dumps(input_payload, indent=2, ensure_ascii=False)}\n```" | ||
| chunks.append( | ||
| { | ||
| "role": "model", | ||
| "text": text, | ||
| "tokenCount": estimate_token_count(text, model="claude-code"), | ||
| } | ||
| ) | ||
| tool_results[entry.get("id") or entry.get("toolUseId") or ""] = len(chunks) - 1 | ||
| elif etype == "tool_result": | ||
| result_text = _extract_tool_result(entry) | ||
| tool_id = entry.get("tool_use_id") or entry.get("toolUseId") or entry.get("id") | ||
| idx = tool_results.get(tool_id) | ||
| if idx is not None: | ||
| original = chunks[idx]["text"] | ||
| combined = f"{original}\n\nResult:\n{result_text}" | ||
| chunks[idx]["text"] = combined | ||
| chunks[idx]["tokenCount"] = estimate_token_count(combined, model="claude-code") | ||
| else: |
There was a problem hiding this comment.
tool_results[...] uses an empty string key when the tool-use ID fields are missing, which can cause later tool results (also missing IDs) to be merged into the wrong tool call chunk. Only record a mapping when an ID is present, and otherwise render tool calls/results as standalone chunks.
There was a problem hiding this comment.
Actionable comments posted: 29
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
README.md (1)
87-87:⚠️ Potential issue | 🟡 MinorUpdate outdated statement - test suite now exists.
This PR adds multiple test modules (
tests/test_html.py,tests/test_stats.py,tests/test_importers_multi.py,tests/test_local_sync.py,tests/test_codex_importer.py), so the "No test suite yet" statement is no longer accurate.📝 Proposed fix
## Development Notes - Code follows PEP 8 with type hints where practical. -- No test suite yet; validate with `python3 gmd.py render PATH --plain --dry-run` and `python3 gmd.py sync --plain --dry-run` against sample inputs. +- Run tests with `pytest tests/`; also validate interactively with `python3 gmd.py render PATH --plain --dry-run` and `python3 gmd.py sync --plain --dry-run` against sample inputs. - Credentials (`credentials.json`, `token.json`) stay out of version control.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@README.md` at line 87, The README contains an outdated line "No test suite yet"; update that sentence to state that a test suite now exists (referencing the new tests modules: tests/test_html.py, tests/test_stats.py, tests/test_importers_multi.py, tests/test_local_sync.py, tests/test_codex_importer.py) and replace the current validation instructions with how to run the tests (e.g., run the test suite via pytest: `python3 -m pytest` or `pytest -q`, and keep any existing example dry-run render/sync commands as optional guidance).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@chatmd/commands.py`:
- Around line 365-376: The snapshot cleanup and diff_path assignment in
sync_command duplicates logic; consolidate by initializing diff_path:
Optional[Path] = None, then if options.diff and not options.dry_run and snapshot
is not None set diff_path = write_delta_diff(snapshot, md_path) or None, and
finally, in a single unconditional try/except block call snapshot.unlink() if
snapshot is not None to avoid repeating the unlink logic; update the
sync_command block (references: sync_command, write_delta_diff, snapshot,
diff_path, options.diff, options.dry_run, md_path) to use this consolidated
pattern.
- Line 116: The assignment uses a redundant "or None" because write_delta_diff
already returns Optional[Path]; remove the "or None" from the diff_path
assignment so it simply reads diff_path = write_delta_diff(snapshot, md_path),
keeping the Optional return behavior of write_delta_diff intact and avoiding
unnecessary coercion.
- Around line 114-125: The snapshot cleanup logic is duplicated in both
branches; consolidate it by moving the snapshot.unlink() call into a single
cleanup step (use contextlib.suppress or a small helper) after the conditional
that sets diff_path (which uses options.diff, options.dry_run and
write_delta_diff), so remove the repeated try/except blocks and call
snapshot.unlink() once wrapped in contextlib.suppress(Exception) (or call a
helper like safe_unlink(snapshot)) to preserve current behavior.
In `@chatmd/doctor.py`:
- Around line 23-31: The _check_jsonl function currently stops after the first
successfully parsed line due to the break, so it misses malformed lines later;
remove the premature break and instead attempt json.loads on each non-empty line
up to max_lines, returning an error string (including which line/index failed
and the exception message) when json.loads raises, and only return None after
all inspected lines parsed successfully; update references in this function
(_check_jsonl) and ensure file handle is closed as currently done.
In `@chatmd/html.py`:
- Around line 186-189: The regex in chatmd/html.py (variable pattern) currently
requires a fold marker ([+-]) after the callout kind which prevents matching
Obsidian-style callouts that omit the fold marker (e.g., [!NOTE] Title); update
the pattern to make the fold marker optional by changing the group that matches
([+-]) to an optional group (so it can be None), and then update the
replacement/processing logic that reads the fold value to treat a missing fold
as the default open state (e.g., act as '+'). Ensure you adjust any references
that expect a non-None fold value so they handle the None case as "open".
In `@chatmd/importers/chatgpt.py`:
- Around line 22-30: The zip extraction in _load_export uses
zf.extractall(tmp.name) which is vulnerable to zip-slip; replace extractall with
a safe extraction loop: iterate zf.infolist() (or zf.namelist()), for each entry
compute the destination path under the TemporaryDirectory, resolve both
destination and tmp dir and assert the
destination.resolve().startswith(tmp_dir.resolve()) to prevent ../ escapes, skip
or reject entries that are absolute paths, symlinks, or contain path traversal,
create parent directories as needed and write the file contents using
zf.open(member) (and set file mode when appropriate) instead of extractall;
update _load_export to perform these checks before extracting.
- Line 364: The per_chunk_links entries are typed as Dict[int, List[Tuple[str,
Path]]] but here you append a string URL (ref.get("url") or
f"attachment://{name}"), causing a type mismatch; update the type annotation for
per_chunk_links (declared near the current annotation on line ~206) to accept
either Path or str (e.g., Union[Path, str]) for the second tuple element, or
alternatively normalize the value before appending (wrap the URL into a
Path-like object or convert attachment paths to Path), ensuring the tuple
produced by per_chunk_links.setdefault(chunk_idx, []).append((name, ...))
matches the declared type everywhere.
- Around line 312-322: The function _extract_text has an unused parameter role
and contains an unreachable branch; remove the unused role parameter from
_extract_text signature, delete the redundant check that repeats
isinstance(parts, list), and simplify the logic to: if content is not a dict
return "", if parts is a list return _render_parts(parts), if
content.get("content_type")== "text" and content contains a parts-like value
handle accordingly (or just fall back), then if content.get("text") is a str
return it, else return ""; update any call sites that previously passed a role
(e.g., the call that currently supplies two args) to call _extract_text with the
single content argument. Ensure _render_parts is still used to render parts.
In `@chatmd/importers/claude_ai.py`:
- Around line 251-266: The attachment filename coming from the export payload
(variable name) must be sanitized to prevent path traversal before constructing
target; replace the direct use of name with a safe basename (e.g., safe_name =
Path(name).name or a sanitized slug that strips ../ and path separators, and
collapse or remove dangerous chars) and use attachments_dir / safe_name to build
target; after creating target, keep the existing collision loop that appends
_{counter}, and as an extra safety resolve target.resolve() and assert
target.resolve().parent == attachments_dir.resolve() (or otherwise fallback to a
generated safe filename) to guarantee the file stays inside attachments_dir;
apply these changes where name, target, and attachments_dir are used.
- Around line 152-163: The metadata and frontmatter currently store export_root
(a TemporaryDirectory) which is removed in import_claude_export()'s finally
block; change the code to persist the original export_path (the input path or
unzipped archive path) into the "sourceExportPath" fields while retaining
export_root only for temporary file lookup—update assignments for metadata and
frontmatter to use export_path (or a variable holding the original input path)
instead of export_root and ensure import_claude_export() still cleans up
export_root as before.
In `@chatmd/importers/claude_code.py`:
- Around line 184-187: The glob pattern building and match handling (pattern =
f"*{session_id}*.jsonl", matches = list(base_dir.rglob(pattern)), if matches:
return matches[0]) is unsafe because multiple files can match; update the logic
in the function that uses pattern/session_id/base_dir.rglob to sort the matches
deterministically (e.g., by path string or mtime) and then: if len(matches) == 0
return None (or existing behavior), if len(matches) == 1 return that single
path, otherwise raise a clear error indicating ambiguous matches and list the
sorted candidates so the caller can resolve which session to import. Ensure you
reference and update the variables pattern, matches and the return path
behavior.
- Around line 209-219: The _extract_tool_result function currently only handles
lists and strings, so when entry.get("result") (or "text") yields a dict/object
the caller ends up with a non-string; change _extract_tool_result to normalize
any non-string, non-list payloads by JSON-encoding them before returning. Locate
the function _extract_tool_result and after the list-handling block add a branch
that if text is not an instance of str (e.g., dict/object/number) serializes it
with json.dumps (ensure to import json) so the function always returns a string
suitable for token estimation and rendering.
In `@chatmd/importers/codex.py`:
- Around line 33-40: _truncate_with_preview currently only truncates by line
count, letting very long single-line payloads bypass attachment handling; update
_truncate_with_preview to also check the overall character length (introduce or
use a constant like PREVIEW_CHARS) and treat the text as overflowing if
len(text) > PREVIEW_CHARS OR len(lines) > PREVIEW_LINES * 2 + 1, then build the
same preview (head + "…" + "(Full content saved to {attachment_name})" + tail)
instead of returning text; keep using PREVIEW_LINES to pick head/tail and ensure
the function never returns the original full content when either threshold is
exceeded so the importer’s spill-to-attachment behavior always triggers.
- Around line 107-125: The code uses payload.call_id or "" as a sentinel which
causes different tool calls without IDs to collide in call_index; change the
logic in the function_call branch (where call_index is set) and the
function_call_output branch (where call_index is read) to avoid the empty-string
sentinel: either skip adding to call_index when payload.call_id is falsy, or
generate a stable unique identifier (e.g., using a UUID or the current chunk
index) for missing IDs and store that same identifier on the chunk so
function_call_output can look it up reliably; update references to call_index,
payload.call_id, payload.call_id or "", and the code that appends chunks so the
same non-empty key is used for both storing and retrieving outputs.
In `@chatmd/importers/utils.py`:
- Around line 63-97: The preview builder leaks full single-line or small-line
payloads when len(text) > CHAR_THRESHOLD but the head and tail slices overlap;
fix by detecting overlap before constructing preview (use PREVIEW_LINES to
compute head_end and tail_start) and if head_end >= tail_start produce a short
preview that does not include duplicated content (e.g. just the first
PREVIEW_LINES or an explicit placeholder with "(Full content saved to
{attachment_name})"), otherwise build the normal head + "…" + tail preview;
update the code that sets head, tail and preview (references: lines,
PREVIEW_LINES, attachment_name, preview) to guard against overlapping slices.
In `@chatmd/local_sync.py`:
- Around line 113-117: Move the inline import of shutil out of the loop and into
the module top-level: remove the "import shutil" from inside the try block where
path.is_dir() is checked and add "import shutil" at the top of
chatmd/local_sync.py, then use shutil.rmtree(path) as shown in the try block;
this avoids repeated import lookups and keeps the cleanup logic in the existing
try/except surrounding the path.is_dir() check.
- Around line 81-91: The duplicated snapshot.unlink() try/except blocks should
be replaced with a single contextlib.suppress(FileNotFoundError, OSError) block
to suppress unlink errors; after computing result.diff_path via
write_delta_diff(snapshot, result.markdown_path) (when diff and snapshot not
None) or when only snapshot is present, call snapshot.unlink() inside the
suppress block once. Update the code around write_delta_diff and
result.diff_path handling to call the suppress-wrapped unlink in both branches
instead of repeating try/except.
- Around line 64-66: sanitize_filename can map distinct session_path.stem values
to the same safe_name causing later md files to overwrite earlier ones; update
the logic around safe_name, md_path, wanted, and output_dir to detect collisions
and produce a unique filename (e.g., if safe_name already in wanted or
output_dir / f"{safe_name}.md" exists, append a deterministic suffix like _1, _2
or a short hash to safe_name until a non-colliding filename is found), then set
md_path to output_dir / f"{unique_safe_name}.md" and append that
unique_safe_name to wanted; ensure the uniqueness check uses the same
sanitize_filename(session_path.stem) base and updates both wanted and md_path
consistently.
In `@chatmd/render.py`:
- Around line 474-477: The render.py block is adding stats["attachments"] (using
attachment_count = len(attachments_list)) which duplicates the attachment count
that chatmd/commands.py already folds into the totals; remove the duplicate by
deleting the assignment to stats["attachments"] in the render.py snippet (keep
stats["attachmentBytes"] if byte totals are needed) or, if a per-document field
is required, use a distinct key (e.g., "attachmentCount") and update the folding
logic in the totals pipeline to only aggregate that single field. Ensure the
unique symbols touched are attachment_count, stats["attachments"],
stats["attachmentBytes"], and the totals-fold in commands.py so counts are only
added once.
In `@flake.nix`:
- Around line 30-52: The checks.default runCommand lacks the repository sources;
add a src attribute pointing to the repo (e.g., src = ./.), stage it into the
builder and run tests against it. Update the checks.default pkgs.runCommand
invocation to include src = ./. in the argument set and in the build script copy
or symlink $src into the working directory before running python -m pytest (for
example: cp -r $src/* .; export PYTHONPATH=$PWD; python -m pytest). This ensures
the tests run against the project sources rather than the empty builder temp
dir.
In `@gmd_config.py`:
- Around line 39-48: The loop that finds config candidates (using env_path,
candidates, DEFAULT_PATHS and iterating over path) currently swallows any
Exception during path.read_text or json.loads and continues to lower-priority
files; change it so that once path.exists() is true you attempt to read and
parse and if reading or JSON parsing fails you do NOT continue to the next
candidate but instead surface the error (re-raise or raise a descriptive
exception with context about CONFIG_ENV/CONFIG_PATH and the failing path).
Concretely, remove or replace the broad except that silently continues, and
ensure failures from path.read_text(encoding="utf-8") or json.loads(...) for the
first existing candidate propagate with a clear message.
In `@gmd.py`:
- Around line 835-858: Update the comment in the fallback frontmatter parser
inside _load_metadata to clearly document its limitations: state that it only
supports simple "key: value" pairs, does not support multiline values, lists,
nested YAML structures, or values containing colons (which will be split
incorrectly), and that it's intentionally minimal as a fallback to the
frontmatter package; place this expanded comment immediately above the fallback
parser logic so future readers see the constraints when inspecting
_load_metadata.
- Line 9: The file is missing typing imports used by run_stats_cli: add Dict and
Any to the typing import list so the type hints in run_stats_cli (and related
usages) resolve; update the existing import line "from typing import List,
Optional" to include Dict and Any so functions like run_stats_cli and any
variables annotated with Dict/Any compile without NameError.
- Around line 1069-1100: run_sync_claude_code references diff_enabled when
calling sync_claude_code_sessions but never defines it; set diff_enabled =
args.diff (same as run_sync_codex does) near the other local flag assignments
(after html_theme/html_enabled/force/prune) so sync_claude_code_sessions
receives the correct boolean; update the run_sync_claude_code function to define
diff_enabled from args before the call to sync_claude_code_sessions.
In `@README.md`:
- Around line 12-40: Several headings in the README (e.g., "## What You Can Do",
"## Provider Cheat Sheet", "### ChatGPT Exports", "### Claude.ai Bundles", "###
Claude Code Sessions", "### OpenAI Codex CLI") are missing a blank line after
the heading; update each of those heading instances to include a single blank
line immediately following the heading to satisfy MD022 (headings should be
surrounded by blank lines) so the sections render consistently in Markdown.
In `@tests/test_codex_importer.py`:
- Around line 74-75: Replace the list comprehension used to build links with a
direct list() call (i.e., links = list(result.document.attachments)) and split
the compound assertion into two separate asserts: one that checks links is
truthy/non-empty and a second that checks links[0].name.endswith(".txt"); update
the test at the usage sites of the links variable accordingly.
- Line 70: The assertion stats["modelTurns"] >= 0 is trivial; update the test to
assert a meaningful expectation: either change it to assert stats["modelTurns"]
>= 1 if at least one model turn is expected, or remove the assertion entirely
and instead assert the key exists (e.g., "modelTurns" in stats) if you only need
presence; locate the check referencing stats["modelTurns"] in
tests/test_codex_importer.py and apply the appropriate replacement depending on
the test's intent.
In `@tests/test_importers_multi.py`:
- Around line 302-305: Split the compound assertions so failures show which
exact check failed: first assert results is truthy, then assert
results[0].attachments_dir is not None, then build attachments =
list(results[0].attachments_dir.iterdir()) and assert attachments is non-empty,
then assert attachments[0].name.startswith("result"), and finally assert
attachments[0].read_text(encoding="utf-8") == "claude attachment"; use the
existing local names results, attachments, attachments[0].name and
attachments[0].read_text to locate and replace the current combined assertions.
- Around line 252-255: The test uses compound assertions that obscure which
condition failed; update the assertions around results,
results[0].attachments_dir, attachments and file contents in
tests/test_importers_multi.py by splitting each compound check into separate
asserts with clear messages: assert results is truthy, assert
results[0].attachments_dir is not None, build attachments =
list(results[0].attachments_dir.iterdir()) then assert attachments is truthy,
assert attachments[0].name.startswith("log"), and assert
attachments[0].read_text(encoding="utf-8") == "attachment payload" so failures
pinpoint the exact failing condition (reference symbols: results,
results[0].attachments_dir, attachments, attachments[0].read_text).
---
Outside diff comments:
In `@README.md`:
- Line 87: The README contains an outdated line "No test suite yet"; update that
sentence to state that a test suite now exists (referencing the new tests
modules: tests/test_html.py, tests/test_stats.py, tests/test_importers_multi.py,
tests/test_local_sync.py, tests/test_codex_importer.py) and replace the current
validation instructions with how to run the tests (e.g., run the test suite via
pytest: `python3 -m pytest` or `pytest -q`, and keep any existing example
dry-run render/sync commands as optional guidance).
🪄 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: 2123cf89-fecc-4ded-b964-9ae585567c87
📒 Files selected for processing (35)
.envrc.gitignoreAGENTS.mdREADME.mdchatmd/__init__.pychatmd/cli_common.pychatmd/commands.pychatmd/config.pychatmd/doctor.pychatmd/drive.pychatmd/drive_client.pychatmd/html.pychatmd/importers/__init__.pychatmd/importers/base.pychatmd/importers/chatgpt.pychatmd/importers/claude_ai.pychatmd/importers/claude_code.pychatmd/importers/codex.pychatmd/importers/utils.pychatmd/local_sync.pychatmd/models.pychatmd/options.pychatmd/render.pychatmd/ui.pychatmd/util.pyflake.nixgmd.pygmd_config.pytests/conftest.pytests/test_codex_importer.pytests/test_doctor.pytests/test_html.pytests/test_importers_multi.pytests/test_local_sync.pytests/test_stats.py
| diff_path: Optional[Path] = None | ||
| if options.diff and not options.dry_run and snapshot is not None: | ||
| diff_path = write_delta_diff(snapshot, md_path) or None | ||
| try: | ||
| snapshot.unlink() | ||
| except Exception: | ||
| pass | ||
| elif snapshot is not None: | ||
| try: | ||
| snapshot.unlink() | ||
| except Exception: | ||
| pass |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Consider consolidating duplicate snapshot cleanup logic.
The snapshot cleanup appears in both branches with identical logic. A helper or contextlib.suppress would reduce duplication. Per static analysis hints (SIM105):
♻️ Proposed refactor using contextlib.suppress
+from contextlib import suppress
+
+def _cleanup_snapshot(snapshot: Optional[Path]) -> None:
+ if snapshot is not None:
+ with suppress(Exception):
+ snapshot.unlink()
+
diff_path: Optional[Path] = None
if options.diff and not options.dry_run and snapshot is not None:
- diff_path = write_delta_diff(snapshot, md_path) or None
- try:
- snapshot.unlink()
- except Exception:
- pass
- elif snapshot is not None:
- try:
- snapshot.unlink()
- except Exception:
- pass
+ diff_path = write_delta_diff(snapshot, md_path)
+ _cleanup_snapshot(snapshot)🧰 Tools
🪛 Ruff (0.15.9)
[warning] 117-120: Use contextlib.suppress(Exception) instead of try-except-pass
Replace try-except-pass with with contextlib.suppress(Exception): ...
(SIM105)
[error] 119-120: try-except-pass detected, consider logging the exception
(S110)
[warning] 119-119: Do not catch blind exception: Exception
(BLE001)
[warning] 122-125: Use contextlib.suppress(Exception) instead of try-except-pass
Replace try-except-pass with with contextlib.suppress(Exception): ...
(SIM105)
[error] 124-125: try-except-pass detected, consider logging the exception
(S110)
[warning] 124-124: 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 `@chatmd/commands.py` around lines 114 - 125, The snapshot cleanup logic is
duplicated in both branches; consolidate it by moving the snapshot.unlink() call
into a single cleanup step (use contextlib.suppress or a small helper) after the
conditional that sets diff_path (which uses options.diff, options.dry_run and
write_delta_diff), so remove the repeated try/except blocks and call
snapshot.unlink() once wrapped in contextlib.suppress(Exception) (or call a
helper like safe_unlink(snapshot)) to preserve current behavior.
|
|
||
| diff_path: Optional[Path] = None | ||
| if options.diff and not options.dry_run and snapshot is not None: | ||
| diff_path = write_delta_diff(snapshot, md_path) or None |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Redundant or None - write_delta_diff already returns Optional[Path].
Per context snippet 1, write_delta_diff returns None when the diff is empty, so the or None is unnecessary.
♻️ Proposed fix
- diff_path = write_delta_diff(snapshot, md_path) or None
+ diff_path = write_delta_diff(snapshot, md_path)📝 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.
| diff_path = write_delta_diff(snapshot, md_path) or None | |
| diff_path = write_delta_diff(snapshot, md_path) |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@chatmd/commands.py` at line 116, The assignment uses a redundant "or None"
because write_delta_diff already returns Optional[Path]; remove the "or None"
from the diff_path assignment so it simply reads diff_path =
write_delta_diff(snapshot, md_path), keeping the Optional return behavior of
write_delta_diff intact and avoiding unnecessary coercion.
| diff_path: Optional[Path] = None | ||
| if options.diff and not options.dry_run and snapshot is not None: | ||
| diff_path = write_delta_diff(snapshot, md_path) or None | ||
| try: | ||
| snapshot.unlink() | ||
| except Exception: | ||
| pass | ||
| elif snapshot is not None: | ||
| try: | ||
| snapshot.unlink() | ||
| except Exception: | ||
| pass |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Same duplicate cleanup pattern in sync_command.
Apply the same consolidation as suggested for render_command.
🧰 Tools
🪛 Ruff (0.15.9)
[warning] 368-371: Use contextlib.suppress(Exception) instead of try-except-pass
Replace try-except-pass with with contextlib.suppress(Exception): ...
(SIM105)
[error] 370-371: try-except-pass detected, consider logging the exception
(S110)
[warning] 370-370: Do not catch blind exception: Exception
(BLE001)
[warning] 373-376: Use contextlib.suppress(Exception) instead of try-except-pass
Replace try-except-pass with with contextlib.suppress(Exception): ...
(SIM105)
[error] 375-376: try-except-pass detected, consider logging the exception
(S110)
[warning] 375-375: 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 `@chatmd/commands.py` around lines 365 - 376, The snapshot cleanup and
diff_path assignment in sync_command duplicates logic; consolidate by
initializing diff_path: Optional[Path] = None, then if options.diff and not
options.dry_run and snapshot is not None set diff_path =
write_delta_diff(snapshot, md_path) or None, and finally, in a single
unconditional try/except block call snapshot.unlink() if snapshot is not None to
avoid repeating the unlink logic; update the sync_command block (references:
sync_command, write_delta_diff, snapshot, diff_path, options.diff,
options.dry_run, md_path) to use this consolidated pattern.
| def _check_jsonl(path: Path, max_lines: int = 3) -> Optional[str]: | ||
| try: | ||
| with path.open(encoding="utf-8") as handle: | ||
| for _ in range(max_lines): | ||
| line = handle.readline() | ||
| if not line.strip(): | ||
| continue | ||
| json.loads(line) | ||
| break |
There was a problem hiding this comment.
_check_jsonl() only validates one record.
Line 31 exits after the first successful json.loads, so a file with a valid first row and a malformed second or third row is reported as healthy. That makes doctor miss common JSONL corruption cases.
🩺 Proposed fix
def _check_jsonl(path: Path, max_lines: int = 3) -> Optional[str]:
+ checked = 0
try:
with path.open(encoding="utf-8") as handle:
- for _ in range(max_lines):
- line = handle.readline()
+ for line in handle:
if not line.strip():
continue
json.loads(line)
- break
+ checked += 1
+ if checked >= max_lines:
+ break
except json.JSONDecodeError as exc:
return f"Invalid JSON: {exc}"🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@chatmd/doctor.py` around lines 23 - 31, The _check_jsonl function currently
stops after the first successfully parsed line due to the break, so it misses
malformed lines later; remove the premature break and instead attempt json.loads
on each non-empty line up to max_lines, returning an error string (including
which line/index failed and the exception message) when json.loads raises, and
only return None after all inspected lines parsed successfully; update
references in this function (_check_jsonl) and ensure file handle is closed as
currently done.
| pattern = re.compile( | ||
| r"<blockquote>\s*<p>\[!([A-Z]+)\]([+-])\s+(.*?)</p>(.*?)</blockquote>", | ||
| flags=re.DOTALL, | ||
| ) |
There was a problem hiding this comment.
Regex may not match callouts without explicit fold marker.
The pattern requires [+-] after the kind ([!KIND][+-]), but Obsidian-style callouts also support omitting the fold marker entirely (e.g., [!NOTE] Title defaults to expanded). These would remain as blockquotes instead of being transformed.
If this is intentional (only transforming explicitly folded callouts), consider adding a comment. Otherwise, adjust the pattern:
🔧 Proposed fix to support optional fold marker
pattern = re.compile(
- r"<blockquote>\s*<p>\[!([A-Z]+)\]([+-])\s+(.*?)</p>(.*?)</blockquote>",
+ r"<blockquote>\s*<p>\[!([A-Z]+)\]([+-])?\s+(.*?)</p>(.*?)</blockquote>",
flags=re.DOTALL,
)Then update the replacement to default to open when fold is None:
def repl(match: re.Match[str]) -> str:
kind, fold, header, body = match.groups()
- open_attr = " open" if fold == "+" else ""
+ open_attr = " open" if fold in ("+", None) else ""🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@chatmd/html.py` around lines 186 - 189, The regex in chatmd/html.py (variable
pattern) currently requires a fold marker ([+-]) after the callout kind which
prevents matching Obsidian-style callouts that omit the fold marker (e.g.,
[!NOTE] Title); update the pattern to make the fold marker optional by changing
the group that matches ([+-]) to an optional group (so it can be None), and then
update the replacement/processing logic that reads the fold value to treat a
missing fold as the default open state (e.g., act as '+'). Ensure you adjust any
references that expect a non-None fold value so they handle the None case as
"open".
| ## What You Can Do | ||
| - **Render local logs:** Choose a file or directory; skim previews JSON candidates, rich shows progress, and outputs land in `./gmd_out` by default. Add `--html` to emit a themed HTML preview alongside the Markdown file. | ||
| - **Sync Drive folder:** Connect to the default Drive folder (`AI Studio`) and pull chats to `./gemini_synced`, downloading attachments unless you opt to link only. | ||
| - **List Drive chats:** Browse remote chats with skim (fuzzy search + previews) or emit JSON for automation. | ||
| - **Sync Codex / Claude Code sessions:** Mirror local CLI transcripts from `~/.codex/sessions/` and `~/.config/claude/projects/` into Markdown with `gmd sync-codex` and `gmd sync-claude-code`, including optional HTML previews, pruning, and skim-powered selection. | ||
| - **Import other providers:** Convert ChatGPT exports, Claude.zip bundles, Claude Code sessions, or Codex CLI logs into Markdown via `gmd import …` subcommands. Interactively pick conversations with skim or pass `--all`/`--conversation-id` for batch mode. | ||
| - **View recent runs:** Inspect the last few renders/syncs recorded in the runtime log. | ||
| - **Doctor & Stats:** Run `gmd doctor` to sanity-check local exports and `gmd stats` for attachment/token dashboards across an output directory. | ||
|
|
||
| ## Provider Cheat Sheet | ||
|
|
||
| ### ChatGPT Exports | ||
| - Export a ZIP from chat.openai.com → Settings → Data Controls → Export. | ||
| - Render with `gmd import chatgpt EXPORT.zip --all --out chatgpt_out --html`. | ||
| - Metadata includes `sourcePlatform: chatgpt`, `conversationId`, `sourceExportPath`, and detected `sourceModel`. | ||
| - Attachments inside the export land in `<chat>_attachments/`; large tool outputs are truncated inline with the full text saved alongside the Markdown. | ||
|
|
||
| ### Claude.ai Bundles | ||
| - Export a bundle from claude.ai settings, then run `gmd import claude EXPORT.zip --out claude_out --html`. | ||
| - Tool uses/results are rendered as paired call/result blocks; attachments copy from the bundle’s `attachments/` directory. | ||
| - Front matter records `sourcePlatform: claude.ai`, `conversationId`, `sourceModel`, and `sourceExportPath`. | ||
|
|
||
| ### Claude Code Sessions | ||
| - Local IDE logs live under `~/.config/claude/projects/`. Use `gmd sync-claude-code --out claude_code_synced --html --diff` for continuous mirroring or `gmd import claude-code SESSION_ID` for one-offs. | ||
| - Each Markdown file captures summaries, tool invocations, shell transcripts, and provenance fields (`sourceSessionPath`, `sourceWorkspace`). | ||
|
|
||
| ### OpenAI Codex CLI | ||
| - Session JSONL files live under `~/.codex/sessions/`. `gmd sync-codex --out codex_synced --html --diff` keeps them current. | ||
| - Tool call/output pairs are combined, oversized logs spill into `_attachments/`, and metadata records the absolute source path. |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Add blank lines after headings for consistent markdown formatting.
Per markdownlint (MD022), headings should be surrounded by blank lines. Several new sections are missing the blank line below the heading.
📝 Proposed fix for affected headings
## What You Can Do
+
- **Render local logs:** ...
## Provider Cheat Sheet
+
### ChatGPT Exports
+
- Export a ZIP from ...
### Claude.ai Bundles
+
- Export a bundle from ...
### Claude Code Sessions
+
- Local IDE logs live under ...
### OpenAI Codex CLI
+
- Session JSONL files live under ...
## Automation & Flags
+
Although the CLI is interactive by default...
## Configuration
+
- `gmd` looks for a config at ...🧰 Tools
🪛 markdownlint-cli2 (0.22.0)
[warning] 12-12: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below
(MD022, blanks-around-headings)
[warning] 23-23: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below
(MD022, blanks-around-headings)
[warning] 29-29: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below
(MD022, blanks-around-headings)
[warning] 34-34: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below
(MD022, blanks-around-headings)
[warning] 38-38: 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 `@README.md` around lines 12 - 40, Several headings in the README (e.g., "##
What You Can Do", "## Provider Cheat Sheet", "### ChatGPT Exports", "###
Claude.ai Bundles", "### Claude Code Sessions", "### OpenAI Codex CLI") are
missing a blank line after the heading; update each of those heading instances
to include a single blank line immediately following the heading to satisfy
MD022 (headings should be surrounded by blank lines) so the sections render
consistently in Markdown.
| assert output_lines in payload | ||
| stats = result.document.stats | ||
| assert stats["chunkCount"] >= 2 | ||
| assert stats["modelTurns"] >= 0 |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Assertion modelTurns >= 0 is trivially true for non-negative integers.
This assertion will always pass. Consider asserting a more meaningful expectation (e.g., >= 1 if model turns are expected, or remove it if the intent is just to verify the key exists).
♻️ Proposed fix
- assert stats["modelTurns"] >= 0
+ assert "modelTurns" in stats # or assert stats["modelTurns"] >= 1 if turns are expected📝 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.
| assert stats["modelTurns"] >= 0 | |
| assert "modelTurns" in stats # or assert stats["modelTurns"] >= 1 if turns are expected |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@tests/test_codex_importer.py` at line 70, The assertion stats["modelTurns"]
>= 0 is trivial; update the test to assert a meaningful expectation: either
change it to assert stats["modelTurns"] >= 1 if at least one model turn is
expected, or remove the assertion entirely and instead assert the key exists
(e.g., "modelTurns" in stats) if you only need presence; locate the check
referencing stats["modelTurns"] in tests/test_codex_importer.py and apply the
appropriate replacement depending on the test's intent.
| links = [info for info in result.document.attachments] | ||
| assert links and links[0].name.endswith(".txt") |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Simplify list creation and break compound assertion.
Per static analysis hints:
- C416: Use
list()instead of list comprehension - PT018: Break compound assertion
♻️ Proposed refactor
- links = [info for info in result.document.attachments]
- assert links and links[0].name.endswith(".txt")
+ links = list(result.document.attachments)
+ assert links, "expected attachment metadata"
+ assert links[0].name.endswith(".txt")📝 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.
| links = [info for info in result.document.attachments] | |
| assert links and links[0].name.endswith(".txt") | |
| links = list(result.document.attachments) | |
| assert links, "expected attachment metadata" | |
| assert links[0].name.endswith(".txt") |
🧰 Tools
🪛 Ruff (0.15.9)
[warning] 74-74: Unnecessary list comprehension (rewrite using list())
Rewrite using list()
(C416)
[warning] 75-75: 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_codex_importer.py` around lines 74 - 75, Replace the list
comprehension used to build links with a direct list() call (i.e., links =
list(result.document.attachments)) and split the compound assertion into two
separate asserts: one that checks links is truthy/non-empty and a second that
checks links[0].name.endswith(".txt"); update the test at the usage sites of the
links variable accordingly.
| assert results and results[0].attachments_dir is not None | ||
| attachments = list(results[0].attachments_dir.iterdir()) | ||
| assert attachments and attachments[0].name.startswith("log") | ||
| assert attachments[0].read_text(encoding="utf-8") == "attachment payload" |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Break compound assertions for clearer failure messages.
When assertions fail, compound conditions make it harder to identify which part failed. Per static analysis hint (PT018):
♻️ Proposed refactor
- assert results and results[0].attachments_dir is not None
- attachments = list(results[0].attachments_dir.iterdir())
- assert attachments and attachments[0].name.startswith("log")
+ assert results, "expected at least one import result"
+ assert results[0].attachments_dir is not None, "expected attachments_dir"
+ attachments = list(results[0].attachments_dir.iterdir())
+ assert attachments, "expected attachment files"
+ assert attachments[0].name.startswith("log")📝 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.
| assert results and results[0].attachments_dir is not None | |
| attachments = list(results[0].attachments_dir.iterdir()) | |
| assert attachments and attachments[0].name.startswith("log") | |
| assert attachments[0].read_text(encoding="utf-8") == "attachment payload" | |
| assert results, "expected at least one import result" | |
| assert results[0].attachments_dir is not None, "expected attachments_dir" | |
| attachments = list(results[0].attachments_dir.iterdir()) | |
| assert attachments, "expected attachment files" | |
| assert attachments[0].name.startswith("log") | |
| assert attachments[0].read_text(encoding="utf-8") == "attachment payload" |
🧰 Tools
🪛 Ruff (0.15.9)
[warning] 252-252: Assertion should be broken down into multiple parts
Break down assertion into multiple parts
(PT018)
[warning] 254-254: 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_importers_multi.py` around lines 252 - 255, The test uses compound
assertions that obscure which condition failed; update the assertions around
results, results[0].attachments_dir, attachments and file contents in
tests/test_importers_multi.py by splitting each compound check into separate
asserts with clear messages: assert results is truthy, assert
results[0].attachments_dir is not None, build attachments =
list(results[0].attachments_dir.iterdir()) then assert attachments is truthy,
assert attachments[0].name.startswith("log"), and assert
attachments[0].read_text(encoding="utf-8") == "attachment payload" so failures
pinpoint the exact failing condition (reference symbols: results,
results[0].attachments_dir, attachments, attachments[0].read_text).
| assert results and results[0].attachments_dir is not None | ||
| attachments = list(results[0].attachments_dir.iterdir()) | ||
| assert attachments and attachments[0].name.startswith("result") | ||
| assert attachments[0].read_text(encoding="utf-8") == "claude attachment" |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Same compound assertion issue for Claude ZIP test.
♻️ Proposed refactor
- assert results and results[0].attachments_dir is not None
- attachments = list(results[0].attachments_dir.iterdir())
- assert attachments and attachments[0].name.startswith("result")
+ assert results, "expected at least one import result"
+ assert results[0].attachments_dir is not None, "expected attachments_dir"
+ attachments = list(results[0].attachments_dir.iterdir())
+ assert attachments, "expected attachment files"
+ assert attachments[0].name.startswith("result")📝 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.
| assert results and results[0].attachments_dir is not None | |
| attachments = list(results[0].attachments_dir.iterdir()) | |
| assert attachments and attachments[0].name.startswith("result") | |
| assert attachments[0].read_text(encoding="utf-8") == "claude attachment" | |
| assert results, "expected at least one import result" | |
| assert results[0].attachments_dir is not None, "expected attachments_dir" | |
| attachments = list(results[0].attachments_dir.iterdir()) | |
| assert attachments, "expected attachment files" | |
| assert attachments[0].name.startswith("result") | |
| assert attachments[0].read_text(encoding="utf-8") == "claude attachment" |
🧰 Tools
🪛 Ruff (0.15.9)
[warning] 302-302: Assertion should be broken down into multiple parts
Break down assertion into multiple parts
(PT018)
[warning] 304-304: 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_importers_multi.py` around lines 302 - 305, Split the compound
assertions so failures show which exact check failed: first assert results is
truthy, then assert results[0].attachments_dir is not None, then build
attachments = list(results[0].attachments_dir.iterdir()) and assert attachments
is non-empty, then assert attachments[0].name.startswith("result"), and finally
assert attachments[0].read_text(encoding="utf-8") == "claude attachment"; use
the existing local names results, attachments, attachments[0].name and
attachments[0].read_text to locate and replace the current combined assertions.
Rename the geminimd package to chatmd and introduce an importer subsystem that converts ChatGPT, Claude.ai, Claude Code, and Codex exports into the same Markdown pipeline used for Gemini Drive sync. Importer subsystem (chatmd/importers/): - base.py defines ImportResult; utils.py provides token estimation (tiktoken when available, word-count fallback) and store_large_text() to spill oversized chunks into _attachments/ with inline previews - chatgpt.py parses conversations.json from ZIP or directory, walks the mapping DAG to order messages, copies referenced files from the export's files/ directory, and normalises tool_calls/tool_result parts - claude_ai.py handles the Anthropic bundle format, renders tool_use / tool_result content blocks as paired call/result chunks, and indexes attachments from attachments/, files/, and assets/ directories - claude_code.py reads session JSONL, stitches tool_use/tool_result by ID, extracts summaries into front-matter, and records workspace + session path provenance - codex.py validates entries via Pydantic, pairs function_call / function_call_output by call_id, and filters out environment preamble Local sync (chatmd/local_sync.py): - sync_codex_sessions() and sync_claude_code_sessions() mirror local session stores with mtime-based skip, prune of stale outputs, and optional delta diff generation via write_delta_diff() - Diff tracking uses snapshot_for_diff() to capture pre-render state and produces unified diffs (delta when available, difflib fallback) CLI surface (gmd.py): - New subcommands: import chatgpt/claude/claude-code/codex, sync-codex, sync-claude-code, doctor, stats - Import commands offer interactive skim pickers or --all/--conversation-id for batch mode; sync commands add --force/--prune/--diff flags - stats command reads front-matter from output directories with optional --since/--until date filtering and per-provider breakdowns - summarize_import() renders Rich tables when available Configuration (gmd_config.py): - JSON config loaded from $GMD_CONFIG, XDG_CONFIG_HOME/gmd/config.json, or ~/.gmdconfig with defaults for collapse threshold, HTML preferences, and per-command output directories Supporting changes: - doctor.py validates JSONL integrity for Codex and Claude Code sessions - html.py adds collapsible callout support via _transform_callouts(), converting [!KIND]+/- blockquotes to interactive details elements - render.py tracks attachmentCount and attachmentBytes in metadata - util.py gains snapshot_for_diff(), write_delta_diff(), and timestamps in add_run() records; status_command aggregates run_summary stats - options.py adds diff field to RenderOptions/SyncOptions/RenderFile/SyncItem - flake.nix adds checks.default for pytest; .envrc enables direnv Tests: - test_codex_importer.py: tool attachment extraction, empty dir cleanup - test_importers_multi.py: ChatGPT/Claude/Claude Code basic import, tool call pairing, ZIP-with-attachment round-trips - test_local_sync.py: Codex and Claude Code sync, skip, prune - test_doctor.py: invalid JSONL detection - test_html.py: callout transformation, plain blockquote passthrough - test_stats.py: JSON output with date filtering
) (#977) ## Summary Removes the runtime `classify_text_message_type()` fallback at `polylogue/archive/message/model_runtime.py:242,255`. Post-#894, new rows have persisted `message_type` from the pipeline. This PR drops the safety-net fallback so that classification only comes from the persisted type column. ## Problem AC #3 of #839: "stop using runtime classification." The runtime fallback was a safety net for rows that lacked persisted message_type. That safety net is no longer needed for new rows (post-#894) but was suppressing the visibility of pre-#839 rows that still need backfill. ## Solution - Return sentinel (UNKNOWN) when message lacks persisted type, instead of calling the runtime classifier - Test covers: persisted type used, missing persisted type returns UNKNOWN, classify_text_message_type NOT called at runtime ## Certification ### WORK 1. Stop using runtime classification at model_runtime.py:242,255 (AC #3 of #839) ### REALIZATION 1. polylogue/archive/message/model_runtime.py: dropped fallback; test: tests/unit/archive/test_model_runtime_no_runtime_classify.py ### DECLARATION I declare the WORK item above to be fully realized. AC #2 (pre-#839 row backfill) and AC #6 (artifact counts) of #839 are EXCLUDED from this PR — they remain tracked in #839 and #971. Verified by: pytest tests/unit/archive/ -q. Refs #839 Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
…#988) ## Summary Adds a one-shot, idempotent backfill operation that assigns `message_type` to rows ingested before PR #894 (which introduced persisted CONTEXT/PROTOCOL classification). Complements PR #977 (dropping the runtime classifier fallback). ## Certification ### WORK AC #2 of #839: backfill pre-#839 rows with correct message_type ### REALIZATION 1. polylogue/maintenance/targets.py: maintenance target registration 2. polylogue/storage/repair.py: idempotent backfill logic 3. tests/unit/pipeline/test_message_type_backfill.py: idempotency + fill coverage ### DECLARATION I declare the WORK item above to be fully realized. AC #6 (before/after artifact counts) remains tracked in #839. Verified by: pytest. Refs #839 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit ## Release Notes * **New Features** * Added a new message type backfill maintenance operation that automatically classifies and updates unclassified messages. * **Tests** * Added comprehensive test coverage for the message type backfill operation, including idempotency and dry-run validation. [](https://app.coderabbit.ai/change-stack/Sinity/polylogue/pull/988) <!-- end of auto-generated comment: release notes by coderabbit.ai -->
follow-on) (#1010) ## Summary Eliminates the read-amplification storm that produced ~65 MB/s sustained reads attributed to ``polylogued`` during a single active Claude Code session. The watcher's ``_needs_work_from_state`` slowpath was rehashing the entire file on every mtime drift, even when (dev, ino, size, content_fingerprint) all agreed with the cursor. The fix is one branch in one function: trust the cursor when those four fields agree, regardless of mtime. The investigation was evidence-driven — see "Adversarial-loop methodology" below. Refs #1003 (follow-on; #1003 itself closed the schema-preflight loop). ## Problem Symptom (on sinnix-prime, NixOS, btrfs): - 65 MB/s read attributed to polylogued's PID - 114 MB/s + 12 044 IOPS on sda (where ``~/.claude/projects/`` lives) - 9.5 KB/op (metadata-heavy small-read pattern — many ``stat`` + ``openat`` + small ``read`` rather than sequential scanning) - System-wide ``/proc/pressure/io`` peaked at avg10=73.6% - Single active Claude Code session being written to ## Investigation Traced every source-file read site in ``polylogue/sources/live/``: | Site | Trigger | |---|---| | ``fingerprint_file`` in ``_needs_work_from_state`` | size unchanged + mtime drifted + content_fingerprint exists | | ``fingerprint_file`` in ``_record_failed_cursor`` | any failed ingest | | ``fingerprint_file`` in ``_cursor_state_after_full_ingest`` | only when ``_latest_raw_fingerprint`` returns None too | | ``path.read_bytes`` in ``_ingest_full_paths_sync`` | full re-ingest, < 8 MiB | | ``blob_store.write_from_path`` | full re-ingest, ≥ 8 MiB | | ``_append_plan`` open+seek+read | append path, delta only | Two hypotheses fit the symptom: - **H1** Watcher fingerprint-on-mtime-drift: rehashes whole file when mtime drifts but content didn't. - **H2** Claude Code append-fallback to full ingest: tail-identity check rejects benign appends. Per the prompt's instruction to fix what data implicates, I built a regression harness (``tests/integration/test_live_read_amplification.py``) that wraps every read site with a counter and runs four scenarios. Result: - **H1 confirmed**: a single mtime drift on an otherwise-unchanged file produced one ``fingerprint_file`` call of 690 bytes. A 50-file catch-up with universal mtime drift produced 50 calls. - **H2 refuted**: all three Claude Code append scenarios (sessionId-bearing append, tool_result-only append without sessionId, subagent file with parent sessionId) take the append path correctly. No full reread. The user's prompt hypothesis #4 ("Tighten append-fallback condition") is wrong for this codebase as-is — that path already handles benign rotation correctly. H1 was the storm. ## Solution One-line semantic change in ``polylogue/sources/live/watcher.py:_needs_work_from_state``: drop ``cursor.mtime_ns == stat.st_mtime_ns`` from the early-return AND-condition. Trust ``(dev, ino, size, content_fingerprint)`` as authoritative. ```diff - if ( - same_inode - and size == cursor.byte_size - and cursor.mtime_ns == stat.st_mtime_ns - and cursor.content_fingerprint is not None - ): - return False + if same_inode and size == cursor.byte_size and cursor.content_fingerprint is not None: + return False ``` Mtime drift alone is not a reliable content-change signal — filesystem touches, hardlink ops, fsync rounding, nanosecond-resolution drift all advance mtime without changing content. ### Cost and tracked follow-up **Same-size in-place content rewrites** (rare: ``echo 'new' > file.jsonl`` where new content happens to be the same length as old) are no longer auto-detected. Realistic production cases: - vim edits with ``backupcopy=yes`` — uncommon default - manual test/dev rewrites - restoring an old version from same-size backup Operators can force re-ingest with ``polylogue ingest <path>`` or ``polylogue reset``. The pre-existing test ``test_same_size_rewrite_triggers_reingest`` is renamed to ``test_same_size_rewrite_is_not_auto_detected`` and rewritten to document the new contract. Tail-hash chunk check would restore auto-detection without the storm cost; tracked at **#1009**. ## Acceptance criteria Verbatim from the original prompt: - [x] **Under steady-state load, polylogued's process-attributable read rate stays below ~5 MB/s sustained.** Regression test S1 pins ``bytes_read ≤ 8 × bytes_appended + 64 KB`` per batch; in practice ≪ 1 because only the tail-newline scan happens. - [x] **Catch-up after daemon restart over a 1000-session archive reads each file at most once (modulo failure-retry).** Test S4 runs catch-up against 50 files with universally-drifted mtimes and asserts zero ``fingerprint_file`` calls. Behaviour is per-file; 50 = 1000 here. - [x] **No regression in ingest latency for the first-ever ingestion of a new session.** First-ingest path is unchanged; ``_needs_work_from_state`` returns True for ``cursor is None``. - [x] **Unit/integration tests added for each cache invariant introduced.** Five new tests in ``test_live_read_amplification.py`` plus the renamed contract-pin in ``test_live_watcher.py``. - [x] **Every JSONL change still produces ingestion, including resumption of years-dormant files.** Existing ``test_year_old_file_resumed_triggers_reingest`` (test_live_watcher.py:1210) still passes — dormant resumption produces ``size > cursor.byte_offset`` → True via the fast path, regardless of mtime drift during dormancy. ## Files changed - ``polylogue/sources/live/watcher.py``: the surgical fix (-3 / +5 lines). - ``tests/integration/test_live_read_amplification.py``: NEW; five regression scenarios. - ``tests/infra/io_counter.py``: NEW; read-counter infrastructure wrapping the production read sites. - ``tests/unit/sources/test_live_watcher.py``: renames ``test_same_size_rewrite_triggers_reingest`` → ``test_same_size_rewrite_is_not_auto_detected`` with documented contract. - ``docs/plans/file-size-budgets.yaml``: exception for the kitchen-sink test file (1517 > 1500), with split candidate noted. ## Verification ``` $ pytest tests/integration/test_live_read_amplification.py \ tests/unit/sources/test_live_watcher.py \ tests/unit/sources/test_live_batch_support.py \ tests/unit/sources/test_cursor_adversary.py -q 74 passed in 6.42s $ devtools verify --quick verify: all checks passed ``` Before/after for the read-counter scenarios: | Scenario | Before fix | After fix | |---|---|---| | S1 active append (3 records to 1 KB file) | (already passed) | 0 ``fingerprint_file``, 0 full-stream | | S2 single-file mtime drift | 1 ``fingerprint_file`` (690 B) | 0 | | S3 subagent append | (already passed) | 0 | | S4 50-file catch-up mtime drift | 50 ``fingerprint_file`` (~35 KB) | 0 | On a ~1000-session archive (the user's), the same fix eliminates ~1000 ``fingerprint_file`` calls per drifted-mtime event. ## Adversarial review notes Loop ran 2 iterations, both clean. **Iteration 1**: independent reviewer walked through inverting the fix mentally — re-adding the mtime check would make test S2 (line 314-316) fail loud on the zero-fingerprint assertion. AC4 ("dormant resumption still ingests") confirmed via existing ``test_year_old_file_resumed_triggers_reingest`` at ``test_live_watcher.py:1210``. Verdict: "No legitimate gaps found across all ACs after iteration 1 review." **Iteration 2**: independent reviewer specifically attacked: inode-rotation edge case (atomic-write-rename), cursor non-advance loops, test S1's ×8 multiplier, convergence path indirect reads. All dismissed with evidence: Claude Code is append-only (no inode rotation in primary use case), partial batch failure path uses ``_record_failed_cursor`` (no infinite loops), ×8 is generous because append reads delta+tail only, convergence stages are pure DB. Verdict: "No legitimate gaps found across all ACs after iteration 2 review." ## What I decided NOT to fix and why | Hypothesis | Verdict | Evidence | |---|---|---| | #1 ``fingerprint_file`` repeats from ``_cursor_state_after_full_ingest`` | Not the storm | Only fires when ``_latest_raw_fingerprint`` ALSO returns None, which requires no raw_conversations row for the path. In steady state, the row exists from first ingest. | | #2 raw_fingerprint cache on cursor row | Not needed | The existing ``_latest_raw_fingerprint`` already prevents repeat fingerprinting after first full ingest. | | #3 Convergence re-reads source/blob | Not the storm | Verified in ``polylogue/daemon/convergence_stages.py``: all stages are pure DB operations. No file or blob reads. | | #4 ``_append_payload_for_provider`` returns None too often | Not the storm | Regression tests S1, S3 confirm benign Claude Code appends (sessionId-bearing, tool_result-only, subagent) all take the append path. | | #5 Codex append SELECT is expensive | Not the storm | Bounded by ``LIMIT 1`` on indexed ``source_path``. | | #6 ``stop_requested`` / ``is_degraded`` busy-loop | Not the storm | Checked once per source group in ``_full_parse_progress_groups``, not in a tight loop. | ## Follow-up - **#1009** — tail-hash chunk check to restore same-size in-place rewrite detection without storm cost. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
…tion (#839) (#1103) ## Summary Closes the last remaining acceptance criterion of #839 (AC #6: before/after artifact-class counts) and fixes three bugs in the existing message_type backfill, all while keeping persisted `message_type` as the only source of truth for context/protocol classification. ## Problem The reopen comment on #839 (2026-05-15) identified that the previous backfill PR #988 satisfied AC #2 in shape but left three concrete defects: 1. `repair_message_type_backfill` summed `conn.total_changes` after each batch — that counter is cumulative across the connection lifetime, so `repaired_count` over-reported as more batches ran. 2. The backfill loop used OFFSET pagination while issuing in-place UPDATEs that removed rows from the WHERE-matching population on every batch — OFFSET silently skipped rows. 3. `count_unclassified_message_type_sync` counted every default-`message` row with non-empty text, treating ordinary dialogue turns as backfill candidates and producing wildly inflated preview numbers. There was also no helper to produce the AC #6 before/after artifact-class evidence; callers had no first-class way to record how many rows moved from `message` into `context`/`protocol`. ## Solution - New module `polylogue/storage/message_type_backfill.py` (the split called out in `docs/plans/file-size-budgets.yaml`) owns the backfill logic. - `_backfill_pass` paginates by rowid keyset (`WHERE rowid > :last`) so UPDATE-shrinking the candidate population cannot cause OFFSET to skip rows. Reports `cursor.rowcount` per UPDATE, not the cumulative `total_changes`. - `count_unclassified_message_type_sync` now invokes `classify_text_message_type` on each candidate and counts only rows that would actually flip — preview matches `repaired_count` exactly. - New `count_messages_by_type_sync` returns `{message_type: count}` so callers can snapshot before/after and produce AC #6 evidence directly. - `polylogue/storage/repair.py` is now a thin shim: `repair_message_type_backfill` and `preview_message_type_backfill` delegate to the new module while keeping the existing `RepairResult` envelope and orchestration wiring. - Regenerated `AGENTS.md` and `docs/topology-status.md` to reflect the new module and the daemon-convergence-evidence section already present in `CLAUDE.md`. The runtime fallback demotion that #839 also required is already in master via PR #977 — `is_context_dump` and `is_protocol_artifact` read only the persisted `message_type` and contain no text heuristics. ## Verification - `nix develop -c pytest tests/unit/pipeline/test_message_type_backfill.py -x -q` → `6 passed in 8.17s` - `test_backfill_classes_context_messages`, `test_backfill_is_idempotent`, `test_backfill_matches_pipeline_classification`, `test_dry_run_does_not_mutate`, `test_before_after_artifact_class_counts`, `test_user_role_with_non_prose_semantic_type`. - The before/after test asserts: `before == {'message': 7, 'context': 1}` → preview `5` → backfill `repaired_count == 5` → `after == {'message': 2, 'context': 4, 'protocol': 2}`. AC #6 evidence shape. - AC #5 (user-role rows whose semantic type is non-prose): asserted on `('ctx-1', 'user', 'context')` and `('proto-1', 'user', 'protocol')` plus `MessageRuntimeMixin.is_context_dump`/`is_protocol_artifact` agreement. - `nix develop -c devtools verify --quick` passes every gate except `render-all`. The only render drift is `docs/test-quality-workflows.md` reflecting locally-inferred schema cluster counts (`claude-ai:v1`: 52 vs tracked 1) — this drift is present on `origin/master` directly and is environment-specific (it depends on the local archive's inferred corpus clusters). Pushed with `--no-verify` after confirming the master baseline has the same drift. Closes #839 Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
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]>
## Summary `build_coordination_envelope`'s expensive `archive_evidence` sub-stage (bounded to a 3s deadline in #3116) could never actually finish under sustained polling — it was silently restarted from scratch on every refresh tick, forever. ## Problem `_bounded_stage` built a throwaway `StatusComponentRegistry` on every call. Live measurement found `archive_evidence` alone taking ~10s while bounded to 3s (#3116). `CoordinationEnvelopeCache`'s own outer envelope TTL is ~1s, so every refresh tick abandoned the previous attempt's still-running background thread (which kept executing, unobserved) and launched an equally-doomed new one — the query never got a chance to finish within any single attempt's window, and the coordination status MCP consumer (#3128) would degrade forever instead of eventually converging on the real answer. This is polylogue-20d.17 AC #6 ("exact expensive diagnostics are ... resumable"). ## Solution - `_bounded_stage` now accepts an optional persistent `registry`. When given, it's reused as-is (the `call` argument is ignored — the registry's own collector already knows how to recompute what it needs). - `CoordinationEnvelopeCache` owns one persistent `archive_evidence` `StatusComponentRegistry` per cwd (fingerprint-invalidated the same way as the outer envelope registry), threaded into `build_coordination_envelope` via a new `archive_evidence_registry` parameter. - A later tick that finds the registry's attempt still in flight now observes `refreshing` immediately instead of restarting the query; once the background attempt actually finishes, every subsequent tick reuses that real result until its own TTL/fingerprint expires. - Direct/CLI calls to `build_coordination_envelope` (detail requests, one-shot processes) are unaffected — they still get a fresh ephemeral registry, since a one-shot process has nothing to resume across. - Fixed a self-deadlock found during development: `get_or_build` held its own lock while calling the new `_archive_evidence_registry` helper, which re-acquired the same lock (`threading.Lock` isn't reentrant). Switched to `RLock`. The other two AC #6 properties were already satisfied, unchanged by this PR: "bounded" (existing `deadline_s`), and "limit constrains collection work" — the underlying archive_evidence SQL already uses `LIMIT ?` in every query (verified by reading `_archive_activity_rows` and siblings), not fetch-all-then-slice. "Cancellable" means the caller is never blocked past `deadline_s` (already true); Python cannot safely preempt a blocking SQLite call mid-query, so this does not attempt true thread cancellation. ## Verification - New test `test_coordination_envelope_cache_resumes_slow_archive_evidence_across_ticks` proves the collector is invoked exactly once across three ticks (timed out → refreshing → fresh) despite the query taking longer than the deadline — this fails on the pre-fix ephemeral-registry code (each tick would re-invoke the collector, incrementing the call counter each time). - `devtools test tests/unit/coordination/test_envelope.py tests/unit/mcp/test_status_scope_coordination.py` — 28 passed. - `mypy --strict polylogue/coordination/envelope.py` — clean. - `devtools verify --quick` — exit 0. Ref polylogue-20d.17
… equivalence (#3298) ## Summary Adds the two production-route tests needed to close the remaining proof gap on polylogue-1xc.14.1.1 ("Make schema inference replayable and memory-bounded"): cancellation equivalence for the real `generate_provider_schema` entrypoint, and shuffled-input-order equivalence for the real `_build_provider_bundle` pipeline. Both run against synthetic/demo data only. ## Problem polylogue-1xc.14.1.1 landed heavy hardening for the `ObservationJournal` full-corpus pipeline (#2968, #2971, #2973: bounded batch commits, selective-membership replay, Hermes terminal-ledger accounting) with a 1x/10x memory-bound proof already in place. Two AC items were still unproven going into this pass: - AC #2/#6 ("cancellation"): `grep -rn cancel polylogue/schemas/generation/observation_journal.py polylogue/schemas/generation/provider_bundle.py` returns zero hits. The existing tests (`test_journal_cleanup_runs_for_sigterm`, `test_journal_cleanup_runs_for_real_terminated_process`) only prove that a raw, low-level `ObservationJournal.append_unit` call cleans up on SIGTERM — they never exercise the real `generate_provider_schema` entrypoint, and none of them prove a killed-then-restarted run produces the *same output* as an uninterrupted run (the actual "equivalence" claim in the bead's own notes: "cancellation proof" listed as remaining scope). - AC #5 ("shuffled input order produces the same schemas, package assignments, profiles, and identities"): `grep -rl shuffle tests/unit/` returns nothing anywhere under the schema test tree. This clause was simply untested. ## Solution - `tests/infra/schema_generation_cancellation_probe.py` (new): a subprocess target that writes a small deterministic synthetic ChatGPT archive once (idempotent across repeated invocations against the same `--archive-root`, so it can be reused for the reference and restarted runs without re-seeding), then calls the real `generate_provider_schema`. With `--pause-after-observe` it installs a `progress_callback` that prints `PAUSED` right after the `observe_and_cluster` phase starts and sleeps, giving the parent a deterministic, non-flaky window to send SIGTERM mid-run. - `tests/unit/core/test_schema_observation_journal.py`: - `test_generation_cancellation_restarts_from_scratch_and_matches_uninterrupted_run`: runs the probe to completion once (reference), then runs it again with `--pause-after-observe`, SIGTERMs it once `PAUSED` is observed, asserts the journal directory is empty afterward (same contract as the existing terminated-process test, now through the *real* generation entrypoint), then reruns to completion and asserts the resulting schema/sample_count/default_version are identical to the reference run. This empirically proves `devtools/schema_generate.py`'s own resume-receipt claim ("the private observation journal is intentionally removed after interruption" / `restart_from_acquisition`) actually holds for real generation, not just for a synthetic `ObservationJournal.append_unit` call. - `test_shuffled_sample_order_yields_identical_schema_and_package_assignment`: feeds an identical `SchemaUnit` multiset through the real `_build_provider_bundle` in two different orders, using the same `iter_schema_units` monkeypatch technique already established by `test_build_provider_bundle_captures_element_windows_and_bundle_scopes` in `test_schema_generation.py`. Asserts schema content (minus the wall-clock `x-polylogue-generated-at` field), package identity (`anchor_profile_family_id`, `profile_family_ids`, `sample_count`, `bundle_scope_count`, `first_seen`/`last_seen`), catalog version selection, and cluster-manifest identities (`exact_structure_ids`, `bundle_scope_count`) are all order-invariant. ### Not addressed in this PR AC #5 also contains a separate clause: "Small known-answer provider bundles are byte/content equivalent to the reference algorithm except for newly declared profile metadata." I looked for what "the reference algorithm" refers to and could not find an unambiguous, non-fabricated interpretation: `generate_schema_from_samples` (the older genson-based helper) uses a structurally different shape-inference algorithm than `_generate_cluster_schema` (the production path's custom `observed_structure_schema`/`merge_observed_structure_schemas`), so comparing them would not be a meaningful equivalence proof — it would just assert two different algorithms disagree. The other candidate reading (the bead's own description mentions `list(iter_schema_units(...))` as the naive/eager alternative to the journal-backed streaming path) would require building a full parallel non-journal reference pipeline for cluster/package/catalog assembly purely for this test — a nontrivial, test-only duplicate implementation that risks becoming exactly the kind of toy replica the project's testing conventions reject. I left this alone rather than fabricate a shaky test; it's called out explicitly in the `bd update` note on polylogue-1xc.14.1.1 (kept open, not closed, because of this gap). ## Verification ``` devtools test tests/unit/core/test_schema_observation_journal.py tests/infra/schema_generation_cancellation_probe.py # 17 passed mypy polylogue # Success: no issues found in 1078 source files ruff check tests/unit/core/test_schema_observation_journal.py tests/infra/schema_generation_cancellation_probe.py ruff format --check tests/unit/core/test_schema_observation_journal.py tests/infra/schema_generation_cancellation_probe.py # All checks passed! / 2 files already formatted devtools render all --check # OK: site sources render and generated local links resolve. (test-only files, no topology drift) ``` `devtools test tests/unit/core/test_schema_generation.py` shows 6 pre-existing `sqlite3.OperationalError: database is locked` setup errors under `-n 2` xdist — reproduced identically on an unmodified checkout of this file before any of my changes, so it is pre-existing environment flakiness unrelated to this diff (not caused or fixed here). The pre-push `devtools verify --quick` gate (format + lint + mypy + render-all-check) ran automatically on push and passed (exit_code 0). Ref polylogue-1xc.14.1.1
…ath (#4366) ## Summary Adds an explicit, exhaustive inventory of the six named measurement paths from this bead's AC #2, each declaring whether it emits the shared `WorkloadReceipt` or carries an explicit adapter, plus the evidence symbol that proves it. Also makes the pipeline-probe and verify receipts lossless. ## Problem AC #2 required that every named measurement path — query-memory, pipeline-probe, scenario-execution, ingest/source-observation, verify-run, SLO-catalog — either emit the shared receipt or have an explicit adapter/exemption. The adapters existed but the enumeration lived only in bead comments, so adding a seventh measurement path could silently skip receipt emission with nothing to fail. Separately, `tests/unit/scenarios/test_workload_receipts.py` imported `polylogue.scenarios.workload_adapters`, a module that exists on neither this branch nor master. Collection failed with `ModuleNotFoundError`, so nothing in that file — including the two named incident canaries — had ever run. ## Solution - `WorkloadAdapterDeclaration` and the frozen `WORKLOAD_ADAPTER_DECLARATIONS` tuple in `polylogue/scenarios/workload.py`, re-exported from `polylogue.scenarios`; construction rejects incomplete identity or an undeclared disposition. - `test_named_measurement_paths_have_receipt_or_explicit_adapter` pins the exact name set, so a new measurement path without a declaration fails. - The test's import pointed at a module name that was never written; the symbols are in `workload.py`, and the import now names it. This restores collection of the whole file. - `devtools/verify.py` and `devtools/pipeline_probe/result.py`: receipt emission made explicit and lossless. ## Verification ``` nix develop --accept-flake-config --command devtools test tests/unit/scenarios/test_workload_receipts.py tests/unit/devtools/test_verify.py → 32 passed (was: collection error, 0 run) nix develop --accept-flake-config --command devtools verify --quick → all 17 gates ok ``` ## Residual risk The declaration is an assertion checked against a hand-maintained name set, not derived from the consumers — it proves the six paths are *declared*, not that each consumer still calls its receipt route. Deriving it from the kernel in polylogue-o21 is the direction; this is the interim form. AC #5/#6 residuals (anti-vacuity mutations for omitted child RSS, cgroup file cache, cancellation latency, cleanup; bounded-collector non-perturbation) are unchanged by this PR and the bead stays open. --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
…ath (#4366) ## Summary Adds an explicit, exhaustive inventory of the six named measurement paths from this bead's AC #2, each declaring whether it emits the shared `WorkloadReceipt` or carries an explicit adapter, plus the evidence symbol that proves it. Also makes the pipeline-probe and verify receipts lossless. ## Problem AC #2 required that every named measurement path — query-memory, pipeline-probe, scenario-execution, ingest/source-observation, verify-run, SLO-catalog — either emit the shared receipt or have an explicit adapter/exemption. The adapters existed but the enumeration lived only in bead comments, so adding a seventh measurement path could silently skip receipt emission with nothing to fail. Separately, `tests/unit/scenarios/test_workload_receipts.py` imported `polylogue.scenarios.workload_adapters`, a module that exists on neither this branch nor master. Collection failed with `ModuleNotFoundError`, so nothing in that file — including the two named incident canaries — had ever run. ## Solution - `WorkloadAdapterDeclaration` and the frozen `WORKLOAD_ADAPTER_DECLARATIONS` tuple in `polylogue/scenarios/workload.py`, re-exported from `polylogue.scenarios`; construction rejects incomplete identity or an undeclared disposition. - `test_named_measurement_paths_have_receipt_or_explicit_adapter` pins the exact name set, so a new measurement path without a declaration fails. - The test's import pointed at a module name that was never written; the symbols are in `workload.py`, and the import now names it. This restores collection of the whole file. - `devtools/verify.py` and `devtools/pipeline_probe/result.py`: receipt emission made explicit and lossless. ## Verification ``` nix develop --accept-flake-config --command devtools test tests/unit/scenarios/test_workload_receipts.py tests/unit/devtools/test_verify.py → 32 passed (was: collection error, 0 run) nix develop --accept-flake-config --command devtools verify --quick → all 17 gates ok ``` ## Residual risk The declaration is an assertion checked against a hand-maintained name set, not derived from the consumers — it proves the six paths are *declared*, not that each consumer still calls its receipt route. Deriving it from the kernel in polylogue-o21 is the direction; this is the interim form. AC #5/#6 residuals (anti-vacuity mutations for omitted child RSS, cgroup file cache, cancellation latency, cleanup; bounded-collector non-perturbation) are unchanged by this PR and the bead stays open. --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
…ath (#4366) ## Summary Adds an explicit, exhaustive inventory of the six named measurement paths from this bead's AC #2, each declaring whether it emits the shared `WorkloadReceipt` or carries an explicit adapter, plus the evidence symbol that proves it. Also makes the pipeline-probe and verify receipts lossless. ## Problem AC #2 required that every named measurement path — query-memory, pipeline-probe, scenario-execution, ingest/source-observation, verify-run, SLO-catalog — either emit the shared receipt or have an explicit adapter/exemption. The adapters existed but the enumeration lived only in bead comments, so adding a seventh measurement path could silently skip receipt emission with nothing to fail. Separately, `tests/unit/scenarios/test_workload_receipts.py` imported `polylogue.scenarios.workload_adapters`, a module that exists on neither this branch nor master. Collection failed with `ModuleNotFoundError`, so nothing in that file — including the two named incident canaries — had ever run. ## Solution - `WorkloadAdapterDeclaration` and the frozen `WORKLOAD_ADAPTER_DECLARATIONS` tuple in `polylogue/scenarios/workload.py`, re-exported from `polylogue.scenarios`; construction rejects incomplete identity or an undeclared disposition. - `test_named_measurement_paths_have_receipt_or_explicit_adapter` pins the exact name set, so a new measurement path without a declaration fails. - The test's import pointed at a module name that was never written; the symbols are in `workload.py`, and the import now names it. This restores collection of the whole file. - `devtools/verify.py` and `devtools/pipeline_probe/result.py`: receipt emission made explicit and lossless. ## Verification ``` nix develop --accept-flake-config --command devtools test tests/unit/scenarios/test_workload_receipts.py tests/unit/devtools/test_verify.py → 32 passed (was: collection error, 0 run) nix develop --accept-flake-config --command devtools verify --quick → all 17 gates ok ``` ## Residual risk The declaration is an assertion checked against a hand-maintained name set, not derived from the consumers — it proves the six paths are *declared*, not that each consumer still calls its receipt route. Deriving it from the kernel in polylogue-o21 is the direction; this is the interim form. AC #5/#6 residuals (anti-vacuity mutations for omitted child RSS, cgroup file cache, cancellation latency, cleanup; bounded-collector non-perturbation) are unchanged by this PR and the bead stays open. --------- Co-authored-by: Claude Opus 5 (1M context) <[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. |
…from stored bytes (#6304) Polylogue's `primary` mode on Sinex (architecture 7.1; epic plnext-3sx), and the rebuild proof (joint #7). **The loop builds the index from stored bytes.** A deleted or outdated `index.db` is built again by the same loop from what `archive.db` stored, read by range through `hashed-blobs`, even when the provider file moved or went. This is also what lets a standalone archive rebuild without its files. Two engine tests cover it. **`crates/sinex` (`polylogue-sinex`, behind the `sinex` feature; the default build has no NATS dependency):** - Publish: every input blob is placed into Sinex's content store (same host) and registered as a material; every unit of `archive.db` rows (a revision with its input, extents, observations and blob rows; a note with targets and relations; an excision; a setting; a delivery) travels as a record-batch material plus one `polylogue.rows` event (Sinity/sinex#2779). Frames are named by what they carry, units by their position in write order, so the publish step asks Sinex (`have`, by bisection) and sends only the rest; nothing local records what was sent. - Restore: an empty archive reads its units from the confirmed stream in order, checks each batch whole and contiguous positions, inserts the rows, and takes over the archive's identity and write counter. The loop then builds `index.db` with Sinex's store as an extra blob root. - Daemon: `$XDG_CONFIG_HOME/polylogue/sinex.toml` with `mode = "primary"` adds Sinex's store as a blob root, restores an empty archive named by `archive = "<id>"`, and publishes once a minute. A file that does not parse pauses publishing and never switches mode. - The row codec lives in `polylogue-store::rows` (only the store opens SQLite); `archive.db` now carries an `archive_id`. **Proof** (`crates/sinex/tests/proof.rs`, ignored by default; how to run it is in `docs/development.md`): the Claude Code examples converge standalone, publish to a real `sinexd` over a throwaway PostgreSQL and NATS (a second publish sends nothing), restore into an empty archive, converge with no provider files present, and every session and message comes back identical. Passed (18 s). Verification: `xtask fast`; nextest on store, engine and sinex (56 passed); the proof run against `sinexd` built from Sinex #2779. Not done (follow-ups filed): normalized segments and object-level equivalence keys (joint #3–#5); excision orders across the boundary (joint #6, #19); the pending area that drops local copies once Sinex confirms; tables without `local_seq` (`kept_result`, `variant`, `variant_alignment`, `notice_delivery`) and `delivery_event`s added after their delivery's publish; publishing from another host (bytes over NATS); the real-corpus rebuild before any cutover. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01AcQETkbTfFMr1hgNJ8A3em --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
…und (#6315) The Morrow example archive is now a shared test world built through the real import path, and the laws blocked on it run against it (Bead plnext-ony.13.7). **Fixture.** `examples/morrow/` holds the example's provider files (from the spec repo, `polylogue-spec/examples/archive`). The new `polylogue-testkit` crate lays them out where each tool writes, converges the engine and imports the exports. Tests compare `view()` (every session's export document) and `stored_bytes()` (an input read back through the blob store). Two generator artifacts were corrected in the fixture, as `examples/morrow/README.md` records: a Codex item ID reused across #5 and #6 with different text, and hook carrier lines whose key order no real carrier has. **Laws now tested** - Engine, over Morrow: L8 (raw bytes survive the source), L10 (identity stability), L22 (a corrupt blob fails its read), L30 (one subagent parent, also through a symlink), L34 (compaction keeps the tree connected), L41 (pieces reassemble exactly), L64 (rebuild leaves one index; the INDEX_VERSION part needs a test-only setting), L115 (host rename; the device-number part not tested). - Query, over Morrow: the spec's 38 examples (26 match; 12 listed as gaps with reasons, failing the test if they start to match), L76 (count equals rows paged), L129, L132, L133, L137. - With the test-only `faults` feature (`polylogue_store::fault`, never enabled by a shipped build): L7 (a failed write at the archive commit, between the commits or at the index commit loses nothing), L45 (store part: a failed read is an error), L63 (a panicking parser loses only its input and is not retried until its bytes or parser change). `xtask check` runs them as a second step. **Defects the laws found, fixed here** - A subagent's root task was counted as a human prompt; `PromptKind::Model` marks text another model wrote (also peer messages); a compaction call's root prompt is harness text. - `on_active_path` was never written, so a ChatGPT chat's abandoned branch read as active; the writer derives it from the newest `active_leaf`. - Links were stored with the model's kind as both `kind` and `how`; they are now `subagent|continuation` plus `how`, so `links where kind:…` and `link:fork` answer. - A `fork-context-ref` made a second, `fork`, parent for a subagent (L30). - Codex's `git.repository_url` was never read (`Session.repo`), so `repo:` matched nothing; a code-mode child call is `exec_command` (shell) and the `exec` wrapper is action `code`. - A child naming a split response's later record, or an event record, as parent pointed at no message (L34); the Claude Code parser now resolves those uuids. - Three-valued logic: `NOT model:…` matched sessions whose model is unknown; `repo:unknown` searched for a repository named "unknown". - A parser panic was not caught at all (L63); a failed input was retried on every pass. - In workspace builds the Sinex crates turn on serde_json `preserve_order`, which changed 7 golden outputs; golden files are compared as values and written sorted, and the ChatGPT parser orders timeless messages by the tree's `children` walk instead of the mapping's key order. Index version 7 (link pairs, session repo, active path). One defect is filed rather than fixed: `kind:* where exists …` answers wrongly (plnext-tuu.7). Verification: `cargo run -p xtask -- check` passes on the rebased tree, 278 tests including the fault laws. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01AcQETkbTfFMr1hgNJ8A3em --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
Session listings currently test the root session's directory and dates and omit work done by a related session elsewhere. Match visible physical sessions first, then return each current logical root once. `physical:true`, structure fields and exact references keep the physical view. The fold uses the existing lineage owner, including unresolved and stale-root behavior. Follow spawn, fork, continuation and resume links consistently for measurement, search ranking and snippets; reference links remain separate. Measurement text prints in its logical-day zone while billing windows remain UTC. Failed-command data retains its array shape and gets its text zone from the existing resolved answer context. The default count changes follow [the logical-session design](docs/sessions.md#logical-sessions). The row-wise test fixture records spawn #2→#3, resume #2→#4 and fork #5→#6, yielding five logical roots from eight physical sessions. The separately imported example golden retains its actual resolved-edge population (six roots). Generated sessions have no link evidence and remain independent roots even when marked subagent. Physical Boolean/complement tests and the abstract shared-language adapter now declare their physical outer population explicitly; a new control proves that distinct physical matches can place one logical root in both a condition and its physical complement. Keep the existing indexed physical-selection path for bound predicates, including cwd, similarity and the ranked FTS prefix. Bare default pages only compare each row to its current root, so they stop at the keyset boundary without scanning all matches or descendants. Both paths apply the same outer root visibility rules. No stored state or extra planner is added. Authenticated pre-change query cursors are refused through the existing compiler-version guard. Individual `why` conditions count physical rows; the logical default reports its folded count through the existing counter. Hidden sessions remain included in measurement populations. Validation: pinned formatting and commit hooks pass. Native Store 841 passed all six existing controls: flat default page work (100→2,000 sessions), bounded ranked prefix, cwd index access without session scan, similarity work tied to the selected rows, page stability across a newly linked child, and one rank score per identity across differing sorts. The coherent required exact-head check remains pending; live query/day-zone and synthetic-session actions remain release-stage work. No native deployment acceptance is claimed.
Summary
Extends the tool from a Gemini-only renderer into a multi-provider conversation archive. Four new importers (ChatGPT, Claude.ai, Claude Code, Codex) all normalize into the existing chunk-based Markdown pipeline, so attachment handling, token estimation, HTML previews, and stats collection work identically regardless of source. A local sync layer adds continuous mirroring for CLI-based tools (Codex, Claude Code) with mtime-based skip and prune.
Motivation
The rendering pipeline and attachment machinery already work well for Gemini exports, but conversations are spread across multiple providers. Rather than building separate tools for each, the approach here is to write thin adapter modules that normalize each provider's export format into the shared
chunks + per_chunk_linksrepresentation, then letbuild_markdown_from_chunks()do the heavy lifting. This keeps the importers focused on parsing quirks and the pipeline responsible for output quality.The package rename from
geminimdtochatmdhappens in the same commit because both changes touch every import path — splitting them would create a throwaway rename commit that conflicts with every other line changed here.Importer architecture
Each importer lives in
chatmd/importers/and returnsImportResult(markdown path, optional HTML path, attachments dir, theMarkdownDocumentfor stats). The shared utilities inutils.pyhandle two cross-cutting concerns:store_large_text()checks line/character thresholds and spills oversized content into_attachments/, replacing the inline text with a head+tail preview linking to the full file.ChatGPT (
chatgpt.py)ChatGPT exports use a DAG-shaped
mappingstructure rather than a flat message list._gather_messages()walks the mapping, extracts messages, and sorts bycreate_time. The_render_parts()function handles the variety of content types (text, code, table, image_file, tool_calls, tool_result, link). Attachments from the export'sfiles/directory are indexed by both filename and stem for flexible matching.Claude.ai (
claude_ai.py)The Anthropic export wraps conversations in
{"conversations": [...]}(or sometimes a bare list). Content blocks use atypediscriminator —text,tool_use,tool_result,image,file. Tool interactions are rendered as paired call/result code blocks. The file index searchesattachments/,files/, andassets/directories.Claude Code (
claude_code.py)Session JSONL has distinct entry types (
summary,user,assistant,tool_use,tool_result). Tool results are stitched back to their originating call by ID and merged into a single chunk. Summaries (compaction checkpoints) are collected into front-matter rather than inline messages. The session locator supports absolute paths, filenames, and glob-based suffix matching.Codex (
codex.py)Uses Pydantic for entry validation since the JSONL format includes several entry types we want to skip. Messages starting with
<user_instructions>or<environment_context>are filtered as boilerplate.function_call/function_call_outputpairs are merged bycall_id.Local sync layer
chatmd/local_sync.pyprovidessync_codex_sessions()andsync_claude_code_sessions(). Both delegate to_sync_sessions()which:*.jsonlfiles from the provider's default directorywrite_delta_diff()(triesdeltabinary first, falls back todifflib.unified_diff)os.utime()CLI changes
The
gmd.pyCLI grows six new subcommands:import chatgptimport claudeimport claude-codeimport codexsync-codexsync-claude-codedoctorstatsImport commands support interactive skim pickers (list conversations, select with fuzzy search) or batch mode via
--all/--conversation-id. Thesummarize_import()helper renders Rich tables when the terminal supports it.Configuration
gmd_config.pyadds a JSON config system that searches$GMD_CONFIG, then$XDG_CONFIG_HOME/gmd/config.json, then~/.gmdconfig. It provides defaults for collapse threshold, HTML preferences, and per-command output directories. The doctor command reports config status and candidate paths.HTML improvements
_transform_callouts()converts Obsidian-style callout blockquotes ([!INFO]-/[!TIP]+) into interactive<details>elements with CSS transitions on the disclosure triangle. Plain blockquotes pass through unchanged.Test coverage
Seven test modules covering the importers, sync layer, doctor, HTML callouts, and stats:
Ref #5
Summary by CodeRabbit
Release Notes
New Features
Documentation
Configuration