Skip to content

test: cover attachment recovery and bulk-export skip paths - #42

Closed
Sinity wants to merge 16 commits into
masterfrom
feature/test/attachment-coverage-and-golden-fixtures
Closed

Sinity wants to merge 16 commits into
masterfrom
feature/test/attachment-coverage-and-golden-fixtures

Conversation

@Sinity

@Sinity Sinity commented Apr 7, 2026 •

Copy link
Copy Markdown
Owner

Summary

I expanded the test suite around the workflows that were still mostly “trust me” paths: partial attachment failures, interactive sync/config flows, HTML transcript rendering, and repeated imports of large ChatGPT / Claude exports. To make those behaviors testable, I also changed the production code in a few targeted places: attachment failures now carry partial results without exploding the pipeline, Drive sync can retry only failed attachments from a previous run, bulk export imports can skip unchanged conversations based on both raw bytes and render configuration, and the HTML/browse surfaces expose richer archive-wide views. The through-line is that I wanted the archive to be resilient under imperfect real-world inputs and to have automated coverage for the recovery path, not just the happy path. The branch also pays down a couple of correctness bugs that the new coverage made obvious, including the misplaced sync JSON block and the watch debounce/stall ordering issue. The result is a suite that exercises the operator workflows that were previously most likely to break silently.

Motivation

Before this branch, the suite had good coverage for simple render and sync behavior, but it still had blind spots exactly where the archive is most operationally interesting.

Attachment failure handling was the biggest one. A failed Drive attachment download could collapse the whole render stage, which is the wrong failure mode for an archival tool. Losing one image or file reference should not prevent the rest of the conversation from being written and indexed.

Interactive flows were another gap. config init and interactive provider/session selection were still largely untested, which meant a regression in the prompt path or subprocess handling would not show up until a human tried it.

Bulk export re-imports were wasting time. ChatGPT and Claude bundle imports could be huge, but if the raw export bytes and render settings were unchanged, we still had to pay the parse/render cost because the importer had no reusable sync state keyed to render config.

HTML output also lagged behind the rest of the archive. Attachments were hard to scan, image-heavy transcripts were clumsy to inspect, and the sidebar/anchor behavior was noisy enough that HTML snapshots were less stable than they needed to be.

I treated those as one branch because the testing work kept uncovering small structural changes that were necessary to express the right behavior in the product code.

Changes by concern

1. Let attachment failures degrade instead of aborting

The key production change is the move from a generic runtime failure to an explicit AttachmentDownloadError shape. That matters because the pipeline can distinguish:

  • the conversation body, which is still renderable
  • the successfully recovered attachments / links
  • the failed attachment subset, which should be reported and retried later

RenderDocumentStage catches the partial-failure form and continues with the usable results. sync_command then records the failed items in run metadata as failedAttachments, including identifiers and error text, without collapsing the whole run into a generic failure.

That richer run metadata is what makes --attachments-only viable. Rather than re-rendering a whole conversation just to retry a couple of files, the next run can target the failed attachment subset directly.

This is the kind of change I wanted the tests to force: the pipeline should preserve as much archive value as possible even when the network or upstream data is imperfect.

2. Add archive-wide browse views that are snapshot-friendly

The new timeline and analytics browse commands are not just UI garnish. They provide structured archive-level views that make it much easier to reason about large datasets in tests and during manual inspection.

  • timeline gives a sortable conversation list with recency, token, word, and attachment stats
  • analytics summarizes provider/model/role/branch hotspots from SQLite
  • both have JSON output for assertions and themed HTML for manual inspection

I paired those with improvements in polylogue/html.py because the HTML transcript view was the other obvious archive-inspection surface. The attachment cards, previews, filter input, lightbox, and anchor fixes make the rendered transcript usable for transcripts that mix text and media instead of treating attachments as an afterthought.

The stability work in HTML is just as important as the new UI. Sorting the attachment sidebar and stripping HTML noise out of generated anchors keeps HTML snapshots meaningful instead of brittle.

3. Skip unchanged bulk-export conversations

The import skip logic uses more than raw input bytes. I added a render-config hash covering the knobs that materially affect the rendered output:

  • collapse threshold
  • HTML mode/theme
  • OCR setting
  • sanitize/redaction setting

A conversation is only skipped when all three conditions hold:

  1. raw content hash matches
  2. render-config hash matches
  3. expected output files already exist

That is a stronger and more correct condition than “same source bytes” alone. If the operator changes HTML mode or OCR, the conversation should re-render even if the underlying export JSON did not move.

Stripped path-dependent metadata keys out of content-hash inputs in document_store.py, because archive relocation should not invalidate content identity. That change helps both the import skip logic and the snapshot story.

4. Put the interactive path under PTY coverage

The PTY harness uses stub gum, sk, bat, and delta binaries so the tests can exercise real CLI control flow without depending on a full external environment. I used that harness to cover:

  • config init
  • interactive sync for Codex / ChatGPT / Claude / Claude Code
  • cancel paths as well as success paths

This is intentionally closer to the user experience than a unit test over a helper function. The bugs I wanted to catch live at the boundary between CLI parsing, prompt selection, environment setup, and filesystem effects.

5. Fix the small bugs the new tests exposed

Two production bugs were worth fixing immediately because the new coverage surfaced them clearly.

The sync JSON success block was indented under an exception branch, so successful runs could not emit the JSON payload that callers expected.

The watch stall logic checked debounce before stall detection, which meant a rapid event stream could keep deferring the stall warning forever. Swapping that order makes --fail-on-stall meaningful even during noisy input bursts.

Split disk estimation into a standalone --disk-estimate preflight instead of making it an accidental side effect of --max-disk.

Testing

This branch is deliberately test-heavy. The most important additions are:

  • golden tool-use + attachment fixtures for ChatGPT and Claude, including HTML
  • PTY interactive coverage for config init and sync flows
  • attachment failure tracking and attachment-only retry tests
  • import-skip coverage for unchanged raw bytes plus unchanged render config
  • watch stall tests that specifically assert the debounce-ordering fix
  • search output tests for --open and --csv
  • analytics / timeline JSON path tests

That combination gives us much better confidence in both operator-facing flows and the recovery story around them.

Notes

Kept the attachment-retry flow targeted at Drive because that is where the failure mode is most acute and where the run metadata already had the right granularity to make a focused rerun useful. The PTY harness also remains intentionally pragmatic rather than pretty; the goal is to exercise the real CLI boundary with enough fidelity to catch regressions, not to build a second interactive framework inside the tests.

- Check stall timeout even when events are debounced.

- Add regression test for --fail-on-stall behavior.

- Update remaining-work tracker.

🤖 Generated with OpenAI Codex CLI
- Add browse timeline to write an HTML conversation timeline and support --json.

- Wire command into browse dispatcher and Click app.

- Add tests and update remaining-work tracker.

🤖 Generated with OpenAI Codex CLI
- Add browse analytics to summarize roles/models and branch hotspots (HTML + --json).

- Wire command into browse dispatcher and Click app.

- Add tests and update remaining-work tracker.

🤖 Generated with OpenAI Codex CLI
- Add unit tests for write_delta_diff (delta output + fallback diff).

- Update remaining-work tracker.

🤖 Generated with OpenAI Codex CLI
- Use local attachment paths in conversation HTML when available.

- Render image attachments as inline previews in the sidebar.

- Update HTML goldens and add coverage.

🤖 Generated with OpenAI Codex CLI
Adds a pexpect-backed PTY test that runs `polylogue config init` end-to-end using stubbed gum/sk helpers, covering default selections and the cancel path.

Also adds pexpect to the Nix dev dependencies.

🤖 Generated with OpenAI Codex CLI
Drive attachment download failures no longer abort the entire chat render; they are recorded in run history and included in resume-from selections.

Also fixes sync drive --json output (previously unreachable due to indentation) and adds regression coverage.

🤖 Generated with OpenAI Codex CLI
Adds sync drive --attachments-only to retry recorded failedAttachments without re-rendering.

Drive attachment download failures now capture per-attachment retry metadata (id/filename/path + slug) so retries can download to the exact placeholder path.

Includes regression coverage and updates the remaining-work tracker.

🤖 Generated with OpenAI Codex CLI
Conversation HTML now has attachment filtering, image lightbox previews, responsive layout tweaks, and a fixed TOC label builder.

Content hashes ignore path-like metadata (output paths, attachment dirs, export paths) so golden fixtures with attachments are stable across machines.

Adds new golden fixtures for ChatGPT/Claude tool calls + attachments and updates golden snapshots.

🤖 Generated with OpenAI Codex CLI
Adds PTY-backed tests for interactive session selection and cancellation paths for polylogue sync codex using stubbed gum/sk helpers.

🤖 Generated with OpenAI Codex CLI
Copilot AI review requested due to automatic review settings April 7, 2026 12:37
@coderabbitai

coderabbitai Bot commented Apr 7, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This PR introduces timeline and analytics CLI browse subcommands for database reporting, adds Drive attachment-only retry support, implements import caching via render config hashes, enhances HTML attachment previews with lightbox UI, refactors disk estimation, and extends test coverage with interactive PTY tests and golden snapshots for tool-augmented conversations.

Changes

Cohort / File(s) Summary
Configuration & Dependencies
nix/python-deps.nix
Added pexpect to dev dependencies for PTY testing support.
New CLI Modules
polylogue/cli/timeline.py, polylogue/cli/analytics.py
Two new browser subcommands: timeline loads conversation/branch statistics from DB and renders as JSON or HTML with search filtering; analytics generates provider/model/role/hotspot stats with optional JSON output or themed HTML report. Both support provider filtering, row limits, and optional editor opening.
CLI Framework Updates
polylogue/cli/click_app.py, polylogue/cli/browse.py
Registered two new browse subcommands (timeline, analytics) with Click decorators accepting provider filters, limits, output paths, themes, and JSON flags. Extended run_browse_cli to dispatch to run_timeline_cli and run_analytics_cli.
Sync Attachment Retry
polylogue/cli/sync.py
Added --attachments-only flag (requires --resume-from) to retry failed Drive attachments. New _retry_drive_attachments_only() processes failedAttachments from prior runs; extended _apply_resume_from() to collect attachment parent IDs; updated Drive JSON/run payloads to persist failedAttachments and attachmentFailures. Unified disk estimation for local sync (disk_estimate or max_disk).
Attachment Error Handling
polylogue/pipeline.py
New AttachmentDownloadError exception carries structured failure data (failed_items dicts with id/filename/path/error) plus current render assets. collect_attachments now captures full failure metadata instead of just IDs.
Render & Command Pipeline
polylogue/cli/render.py, polylogue/commands.py
Render now supports disk_estimate flag and conditional disk-preflight block with JSON fields (diskEstimateBytes, diskFreeBytes, maxDiskGiB). Commands catch AttachmentDownloadError, switch to error-provided links, record failures, and emit warnings. Sync emits periodic plain-text progress messages and aggregates attachment failures into run payloads (attachmentFailures, failedAttachments).
Import Caching
polylogue/importers/chatgpt.py, polylogue/importers/claude_ai.py, polylogue/util.py
Added _render_config_hash() to both importers; new import_sync_state_* functions (get, set, key) in util persist hash/timestamp metadata to database. Importers now skip rendering when raw content and render-config hashes match stored values and output files exist. New helpers: format_duration(), import_sync_state_key/get/set.
HTML Rendering & UI
polylogue/html.py
Enhanced attachment cards with icon, size subtitle, thumbnails with data attributes, and searchable data-att field. New sidebar filter input toggles attachment visibility. Added lightbox modal for image preview with click/escape/backdrop close. Updated TOC generation to strip HTML tags from headings. Sorted attachments deterministically; URL-quote links when local paths exist. Computed new fields (preview_src, ext, kind, icon, attachmentBytes).
Metadata & Hashing
polylogue/document_store.py
_metadata_without_content_hash() now strips path/location-dependent fields (output/html/session/source/bundle/export paths, hash digests) from serialized metadata before computing contentHash, making hashes independent of filesystem locations.
Watch & Progress
polylogue/cli/watch.py, polylogue/local_sync.py
Watch stall detection now triggers only once per stalled period and resets after successful sync. Replaced custom _fmt_eta() with shared format_duration() for progress ETA formatting. Export-bundle progress is now index-driven and rate-limited via _maybe_plain_progress().
Golden Test Data
tests/golden/*, tests/golden_html/*
Added golden snapshots for tool-augmented ChatGPT and Claude conversations (markdown + HTML). Updated contentHash values in existing golden files to reflect new hashing logic.
Test Coverage
tests/test_*.py
Comprehensive test additions: analytics/timeline CLI tests, attachment retry/failure tests, disk-estimate render tests, import skip logic tests, interactive PTY harness with pexpect, HTML attachment preview tests, search "open" behavior, delta-diff fallback, and watch stall handling. 12+ new test files/extensions.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Possibly related issues

Poem

🐰 A timeline flows and analytics gleam,
Attachments preview in a lightbox dream!
Failed downloads retry with flags so keen,
Golden snapshots prove the render machine.
Hashes cached, the imports skip with grace—
The code hops forward at a quickened pace! 🌟

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 1.71% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed Title is clear and specific about the main focus—covering attachment recovery and bulk-export skip paths—which aligns with the core production changes and test additions in the changeset.
Description check ✅ Passed The pull request description is comprehensive and well-structured, covering all major sections: summary, motivation, detailed changes by concern, testing approach, and notes on design decisions.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/test/attachment-coverage-and-golden-fixtures

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

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR strengthens Polylogue’s operational resilience (partial attachment failures, retry-only attachment sync, idempotent bulk import skipping) and adds substantial automated coverage for previously under-tested interactive/browse workflows and HTML rendering stability.

Changes:

  • Add partial attachment-failure propagation through the pipeline + record failed attachment metadata for later retries (--attachments-only).
  • Add new browse timeline and browse analytics commands (HTML + JSON) backed by the SQLite state DB.
  • Add import-skip logic for ChatGPT/Claude exports keyed by raw content hash + render-config hash, plus extensive new tests (golden, PTY/pexpect, watch stall ordering).

Reviewed changes

Copilot reviewed 42 out of 42 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
polylogue/pipeline.py Introduces AttachmentDownloadError carrying partial attachment results instead of aborting.
polylogue/commands.py Continues render/sync when attachments partially fail; records failed attachment details in run metadata.
polylogue/cli/sync.py Adds Drive --attachments-only retry path and improves --resume-from to include attachment failures.
polylogue/importers/chatgpt.py Adds skip-when-unchanged logic using raw hash + render-config hash + existing outputs.
polylogue/importers/claude_ai.py Same skip-when-unchanged logic for Claude exports.
polylogue/util.py Adds import sync-state helpers and a shared format_duration() utility.
polylogue/html.py Improves attachment display (previews, filtering, lightbox) and stabilizes anchors/TOC text.
polylogue/cli/timeline.py Adds archive-wide timeline browse view (HTML/JSON).
polylogue/cli/analytics.py Adds archive-wide analytics browse view (HTML/JSON).
polylogue/cli/watch.py Fixes stall detection ordering so --fail-on-stall triggers even during debounce.
polylogue/document_store.py Makes content hashes stable across archive relocation by stripping path-dependent metadata keys.
polylogue/local_sync.py Reuses shared duration formatting and adds plain progress reporting for export bundles.
polylogue/cli/click_app.py Wires new browse commands + adds --attachments-only and --disk-estimate options.
polylogue/cli/render.py Adds disk estimate reporting in JSON output and separates --disk-estimate from --max-disk enforcement.
nix/python-deps.nix Adds pexpect for PTY/interactive CLI tests.
tests/* Adds broad coverage: watch stall behavior, attachment-only retry, resume-from attachment selection, search --open/CSV, browse JSON paths, PTY harness, and new golden snapshots.

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

Comment thread polylogue/cli/sync.py
Comment on lines +182 to +190
if not filename:
filename = sanitize_filename(att_id)
rel_path = str(Path("attachments") / filename)

target_path = (convo_dir / rel_path).resolve()
attempted += 1
if target_path.exists() and not force:
skipped += 1
continue

Copilot AI Apr 7, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_retry_drive_attachments_only() builds target_path = (convo_dir / rel_path).resolve() from failedAttachments run metadata without validating that rel_path stays within the conversation directory. If a run record is corrupted/edited (or originates from an unexpected source), an absolute path or ../ traversal could cause attachment retries to write outside the archive root.

Recommendation: treat rel_path as untrusted input and enforce that the resolved path is under convo_dir (e.g., reject absolute paths / path traversal, or compute target_path = (convo_dir / rel_path).resolve() and then verify target_path.is_relative_to(convo_dir.resolve()) before downloading).

Copilot uses AI. Check for mistakes.
Comment thread polylogue/util.py
Comment on lines +178 to +200
def import_sync_state_key(provider: str, conversation_id: str) -> str:
material = f"{provider}:{conversation_id}".encode("utf-8")
digest = hashlib.sha256(material).hexdigest()
return f"import.sync.{digest}"


def get_import_sync_state(provider: str, conversation_id: str) -> Optional[dict]:
raw = _get_meta_value(import_sync_state_key(provider, conversation_id))
if not raw:
return None
try:
data = json.loads(raw)
return data if isinstance(data, dict) else None
except Exception:
return None


def set_import_sync_state(provider: str, conversation_id: str, payload: dict) -> None:
payload = dict(payload)
payload.setdefault("provider", provider)
payload.setdefault("conversationId", conversation_id)
_set_meta_value(import_sync_state_key(provider, conversation_id), json.dumps(payload, sort_keys=True, separators=(",", ":")))

Copilot AI Apr 7, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

get_import_sync_state() / set_import_sync_state() always read/write state_meta via open_connection(None), which targets the default DB path from XDG_STATE_HOME. Importers now also open a possibly different DB via registrar.database.resolve_path() for raw_imports checks. If a caller provides a non-default ConversationRegistrar/DB path (supported by create_default_registrar(database_path=...)), the skip logic can consult a different database for sync state than the one holding raw_imports + conversations.

Recommendation: thread the state DB path through these helpers (e.g., optional db_path/conn parameter), or move the sync-state storage to a table keyed within the registrar DB so all importer state lives together.

Copilot uses AI. Check for mistakes.
Sinity added a commit that referenced this pull request Apr 7, 2026
…arness (#42)

Extend the test suite to cover attachment failure recovery, incremental
import skip logic, and interactive CLI flows. Production code changes
make these scenarios testable and add two browse subcommands.

Attachment failure recovery (pipeline.py, commands.py, cli/sync.py):
- Replace hard RuntimeError on download failure with AttachmentDownloadError
  that carries partial results (per_index_links, attachments, failed_items)
- RenderDocumentStage catches AttachmentDownloadError, continues with
  partial attachments, and records failures in pipeline context
- sync_command aggregates per-conversation attachment failures into run
  payload as failedAttachments list with per-item id/filename/path/error
- New --attachments-only flag retries just failed Drive attachments from
  a previous run without re-rendering conversations
- _apply_resume_from() parses failedAttachments alongside failedChats

Import skip optimization (importers/chatgpt.py, importers/claude_ai.py):
- Compute render config hash from collapse/html/theme/ocr/sanitize params
- Skip re-import when raw content hash, render config hash, and output
  files are all unchanged; --force overrides
- Track sync state via set_import_sync_state() keyed by provider+conv_id

HTML viewer (html.py):
- Image lightbox with Esc-close, click-outside-dismiss, and open-in-tab
- Attachment cards show type icon, thumbnail preview, and filter input
- Responsive layout collapses sidebar below 860px breakpoint
- TOC link text strips dynamically-added anchor buttons via cloneNode
- _anchorize() strips HTML tags before generating anchor IDs

Browse commands (cli/analytics.py, cli/timeline.py):
- analytics: provider/model/role/branch-hotspot aggregates from SQLite
- timeline: sortable conversation list with token/word/attachment stats
- Both emit JSON (--json) or themed HTML with client-side filtering

Content hash stability (document_store.py):
- Strip path-dependent metadata keys (outputPath, htmlPath, sessionPath,
  sourceExportPath, bundle_path, export_root) from hash computation so
  content hashes are stable across machines and archive locations

Tests:
- Golden tool+attachment fixtures for ChatGPT and Claude providers
- Interactive PTY harness using pexpect with stub gum/sk/bat/delta
- Attachment failure tracking without pipeline abort
- Attachment retry-only flow with stub Drive client
- Import skip on unchanged raw+render config for both providers
- Watch stall detection before debounce skip
- Search CSV output, browser/editor open dispatch
- Analytics and timeline CLI JSON output paths

Bug fixes:
- cli/sync.py: fix JSON output block indentation (was nested inside
  except clause, making it unreachable on success)
- cli/watch.py: evaluate stall timeout before debounce skip so
  --fail-on-stall fires even during rapid event bursts; reset stalled
  flag after successful sync to avoid duplicate warnings
- Disk estimate logic extracted to standalone --disk-estimate flag
  independent of --max-disk

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5fad7fc908

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread polylogue/cli/sync.py Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 20

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@polylogue/cli/click_app.py`:
- Around line 263-264: The force branch bypasses the disk-usage checks because
run_render_force(...) is called without passing the disk_estimate and max_disk
flags; update the control flow in click_app.py so the preflight disk check runs
for the --force path or forward the flags into run_render_force (add parameters
disk_estimate and max_disk to run_render_force and propagate them from the click
command), and ensure the preflight logic that uses disk_estimate and max_disk is
invoked before exiting to run_render_force or inside run_render_force itself.

In `@polylogue/cli/render.py`:
- Around line 81-97: The code treats max_disk falsily so 0.0 is ignored and also
measures free space on Path.cwd() instead of the render destination; change the
boolean checks to explicit None checks (use "if disk_estimate or max_disk is not
None" and later "if max_disk is not None") so --max-disk 0.0 is honored, and
compute free_bytes by calling shutil.disk_usage on the resolved render
destination path (use the output path variable, e.g. args.out or the function's
out/output variable, falling back to Path.cwd() if unset) instead of Path.cwd(),
then pass free_bytes and max_disk (including zero) into the UI/json output and
to preflight_disk_requirement(projected_bytes=projected, limit_gib=max_disk,
ui=ui).

In `@polylogue/cli/sync.py`:
- Around line 175-208: When rel_path is None the code calls
drive.attachment_meta(att_id) twice; to fix, cache and reuse the metadata: when
rel_path is None, call meta = drive.attachment_meta(att_id) once, derive
filename/rel_path from meta and keep that meta for later touch_mtime; when
rel_path is not None, DO NOT call attachment_meta up-front — instead call meta =
drive.attachment_meta(att_id) only after a successful
drive.download_attachment(att_id, target_path) if you need it for
drive.touch_mtime(target_path, meta.get("modifiedTime")). Update the logic
around rel_path, meta, drive.download_attachment and drive.touch_mtime so
attachment_meta is invoked at most once per attachment.

In `@polylogue/cli/timeline.py`:
- Line 153: run_timeline_cli is passing an env but _load_rows always calls
open_connection(None), so the archive DB selected by env is ignored; update the
calls to _load_rows in run_timeline_cli (and the other call sites noted) to
accept and forward the CommandEnv (e.g., pass env) and modify _load_rows to call
open_connection(env) instead of open_connection(None) so the function opens the
DB for the provided env; ensure function signature changes (and any callers) and
that any tests/multi-archive usage now use the injected env when resolving
providers.

In `@polylogue/commands.py`:
- Around line 804-819: The normalization loop that builds cleaned attachment
entries from att_failures currently drops the entry's "error" field; update the
logic in the block that iterates att_failures (the loop that builds cleaned:
List[Dict[str, str]]) to copy an "error" value from entry into item when present
(e.g., if isinstance(entry.get("error"), str) and entry["error"].strip():
item["error"] = entry["error"].strip()), so the resulting cleaned list preserves
error messages before it is assigned to failedAttachments/run metadata.
- Around line 715-718: The code in _maybe_plain_progress reads env.ui.plain
which isn't guaranteed by CommandEnv._ensure_ui_contract(), causing
AttributeError for lightweight UIs; change the guard to use a safe attribute
check like getattr(env.ui, "plain", False) (or hasattr(env.ui, "plain") and
default to False) so the function returns early when plain isn't present or
total <= 0. Update the conditional in _maybe_plain_progress to use
getattr(env.ui, "plain", False) (and keep the total <= 0 check) to avoid relying
on env.ui.plain being part of the fallback UI contract.

In `@polylogue/html.py`:
- Around line 483-490: Replace the silent try/except block around converting
att.size_bytes with a contextlib.suppress to make the intent explicit: import
contextlib, and in the loop over attachments_sorted wrap the int(att.size_bytes
or 0) conversion and addition to attachment_total_bytes with
contextlib.suppress(ValueError, TypeError) (or a broader Exception if desired)
so invalid or non-numeric size_bytes are ignored cleanly before setting
metadata_rows["attachmentBytes"].
- Around line 567-574: The annotation Optional[str] in _attachment_preview_src
refers to Optional which is not imported; fix by importing Optional from typing
(add Optional to the existing typing import list) or change the annotation to
use native union syntax (str | None) in the _attachment_preview_src function to
avoid the NameError at module load time.

In `@polylogue/importers/chatgpt.py`:
- Around line 39-56: The _render_config_hash function is duplicated; extract it
to a single shared helper (e.g., create render_config_hash in importers/utils.py
or importers/base.py) and replace the copies in claude_ai.py and chatgpt.py with
an import and call to that shared function; ensure the helper retains the same
signature/behavior (collapse_threshold, collapse_thresholds, html, html_theme,
attachment_ocr, sanitize_html) and uses the same compute_hash/json serialization
so both modules call render_config_hash (or _render_config_hash if you keep the
name) for consistent hashing.

In `@polylogue/local_sync.py`:
- Around line 621-624: The helper _maybe_plain_progress currently dereferences
ui.plain unconditionally which can raise on injected UI stubs lacking a plain
attribute; update the guard in _maybe_plain_progress (used by
_sync_export_bundles) to safely check for the attribute, e.g. treat plain as
optional by using getattr(ui, "plain", False) (or hasattr check) so the
condition becomes: if not ui or not getattr(ui, "plain", False) or total <= 0:
return.

In `@polylogue/pipeline.py`:
- Around line 152-161: The code currently registers every attachment as local by
always calling collector.add_local(...) even when the download failed; change
the logic to only call collector.add_local when the download actually succeeded
(use the boolean/result from download_attachment), and for failed downloads
leave out add_local and instead record the failure in failures (as already done)
or emit a dedicated remote/failed placeholder path (e.g., add a remote/failed
entry via your existing remote-add API or a new collector method) so broken
local paths are not inserted into per_index_links/attachments; update the block
around collector.add_local, snapshot_drive_metrics, and failures to be
conditional on the download success flag.

In `@polylogue/util.py`:
- Around line 184-199: The get_import_sync_state and set_import_sync_state
helpers currently call _get_meta_value/_set_meta_value which use the
process-default DB; change these functions to accept and thread an explicit
state repository or active database handle (e.g., add an optional state_repo or
db_path parameter) and pass that through into the underlying _get_meta_value and
_set_meta_value calls (and into import_sync_state_key if it needs the repo
context) so the meta values are read/written from the caller's active archive DB
instead of the global default; update any callers to supply the active state
repository.

In `@tests/golden_html/claude-tool.html`:
- Around line 200-203: The search input with id "client-search" (class
"search-input") currently has only placeholder text and no accessible name;
update the HTML renderer to provide an accessible name by emitting either a
visible <label for="client-search">Transcript filter</label> associated with
that input or by adding an appropriate aria-label (e.g., aria-label="Filter
transcripts") to the input element, ensure the label text is descriptive, and
then refresh the golden snapshot so tests reflect the change.

In `@tests/test_commands_logic.py`:
- Around line 279-287: The test currently only asserts the top-level
failedAttachments entry exists and its parent id; strengthen it by asserting the
nested failure detail fields are present and correctly typed/valued: inspect
result.failed_attachments (and record["failedAttachments"]) to assert each
failure dict contains keys like "fileId" or "id", "fileName" or "name", "path",
and "error" (or whichever keys your payload uses), assert their types (str) and
that the id/value matches "drive-1" and error is non-empty; update the
assertions around failed_attachments and record to validate these nested fields
for both the in-memory result and the persisted record.

In `@tests/test_golden_html_snapshots.py`:
- Around line 79-98: Combine the duplicated test functions into one pytest
parametrized test to drive fixture/golden combos: replace the separate
test_golden_chatgpt_tool_html and the other test (lines 120-139) with a single
test decorated with pytest.mark.parametrize that yields tuples like
(fixture_dir, golden_filename, html, html_theme, collapse_threshold). Inside the
single test reuse the existing logic and calls to import_chatgpt_export,
_render_slug, and _assert_golden_html but use the param values (fixture_dir ->
passed to _rel(fixtures / ...), golden_filename -> golden_dir / ...). Keep
monkeypatch.setenv("POLYLOGUE_FIXED_NOW", FIXED_NOW), creation of out_dir,
results handling and slug extraction identical; ensure parameter names match the
tuple order and preserve force=True. This removes duplication while keeping
import_chatgpt_export, _render_slug, and _assert_golden_html as the single
points of behavior verification.

In `@tests/test_golden_snapshots.py`:
- Around line 72-90: These two nearly-identical tests (e.g.,
test_golden_chatgpt_tool) should be combined into a parametrized pytest to avoid
duplication: replace the separate functions with a single test function
decorated with pytest.mark.parametrize that yields tuples of (fixture_subdir,
importer_fn or import parameters, golden_filename) and then call
import_chatgpt_export (or the appropriate importer) with the parametrized
inputs, compute slug and db_path the same way, call _render_slug, and assert
with _assert_golden using the parametrized golden target; ensure the new param
set covers both existing cases referenced around lines 72–90 and 113–131 so only
the fixture/golden values change per parameter.

In `@tests/test_html.py`:
- Around line 56-63: The test's attachment fixture is inconsistent:
local_img.write_bytes(b"\x89PNG\r\n\x1a\n") writes 8 bytes but AttachmentInfo is
created with size_bytes=9; update the fixture so size_bytes matches the actual
written bytes (e.g., set size_bytes=8) or change the written payload to match 9
bytes; locate the AttachmentInfo construction in tests/test_html.py (symbols:
local_img, AttachmentInfo, size_bytes) and make the size_bytes value equal to
the actual byte length.

In `@tests/test_importers_multi.py`:
- Around line 115-179: Update the
test_import_chatgpt_export_skips_when_unchanged test to assert that skipping
only happens when expected outputs exist by adding a step that removes the
generated output (e.g., delete the markdown/html file or the entire
out_dir/markdown_path created by the first run) before calling
import_chatgpt_export a third time; call import_chatgpt_export (function name)
after removing the output and assert the result is not skipped (use the same
collapse_threshold/html/html_theme/force arguments as in the other calls) so the
test verifies that absence of the expected output prevents the "skipped" path.

In `@tests/test_search_open.py`:
- Line 77: The compound assertion using the opened variable should be split into
two explicit checks: replace the single assertion that combines existence and
content with first asserting that opened is truthy (e.g., assert opened) and
then asserting the anchor of the first element (e.g., assert
opened[0].endswith("#msg-2")); update the assertion in the test (around the
opened variable in tests/test_search_open.py) to these two separate asserts so
failures clearly indicate emptiness vs wrong anchor.
- Around line 103-104: The test uses a hardcoded Path("/tmp/conversation.md")
which is platform-specific and triggers Ruff S108; update the test to use the
pytest tmp_path fixture instead (e.g., create a Path via tmp_path /
"conversation.md") and pass that to _hit_for_path so the hit variable is created
from a temp-file path; also ensure the test function signature includes the
tmp_path parameter and that any SimpleNamespace setup that depends on this path
uses the tmp_path-derived Path.
🪄 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: 0b36a817-1849-4a80-abee-56ccf3e5b2d0

📥 Commits

Reviewing files that changed from the base of the PR and between ef527c9 and 5fad7fc.

📒 Files selected for processing (42)
  • nix/python-deps.nix
  • polylogue/cli/analytics.py
  • polylogue/cli/browse.py
  • polylogue/cli/click_app.py
  • polylogue/cli/render.py
  • polylogue/cli/sync.py
  • polylogue/cli/timeline.py
  • polylogue/cli/watch.py
  • polylogue/commands.py
  • polylogue/document_store.py
  • polylogue/html.py
  • polylogue/importers/chatgpt.py
  • polylogue/importers/claude_ai.py
  • polylogue/local_sync.py
  • polylogue/pipeline.py
  • polylogue/util.py
  • tests/golden/chatgpt-basic.md
  • tests/golden/chatgpt-tool.md
  • tests/golden/claude-basic.md
  • tests/golden/claude-code-basic.md
  • tests/golden/claude-tool.md
  • tests/golden/codex-basic.md
  • tests/golden_html/chatgpt-basic.html
  • tests/golden_html/chatgpt-tool.html
  • tests/golden_html/claude-basic.html
  • tests/golden_html/claude-code-basic.html
  • tests/golden_html/claude-tool.html
  • tests/golden_html/codex-basic.html
  • tests/test_analytics_cli.py
  • tests/test_cli_wrappers.py
  • tests/test_commands_logic.py
  • tests/test_delta_diff.py
  • tests/test_drive_attachments_only.py
  • tests/test_golden_html_snapshots.py
  • tests/test_golden_snapshots.py
  • tests/test_html.py
  • tests/test_importers_multi.py
  • tests/test_interactive_harness.py
  • tests/test_resume_from.py
  • tests/test_search_open.py
  • tests/test_timeline_cli.py
  • tests/test_watch_cli.py

Comment on lines +263 to 264
@click.option("--disk-estimate", is_flag=True, help="Print projected disk usage before running")
@click.option("--max-disk", type=float, help="Abort if projected disk use exceeds this many GiB (approx)")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

render --force bypasses the new disk guardrails.

Line 277 exits through run_render_force(...), which never receives disk_estimate or max_disk. As written, polylogue render --force --max-disk ... will ignore the safety limit entirely. Please run the preflight before this branch or plumb the flags into run_render_force.

Also applies to: 276-280

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/cli/click_app.py` around lines 263 - 264, The force branch bypasses
the disk-usage checks because run_render_force(...) is called without passing
the disk_estimate and max_disk flags; update the control flow in click_app.py so
the preflight disk check runs for the --force path or forward the flags into
run_render_force (add parameters disk_estimate and max_disk to run_render_force
and propagate them from the click command), and ensure the preflight logic that
uses disk_estimate and max_disk is invoked before exiting to run_render_force or
inside run_render_force itself.

Comment thread polylogue/cli/render.py
Comment on lines +81 to 97
disk_estimate = bool(getattr(args, "disk_estimate", False))
max_disk = getattr(args, "max_disk", None)
if disk_estimate or max_disk:
projected = len(inputs) * 5 * 1024 * 1024 # rough 5MiB per file heuristic
from ..util import preflight_disk_requirement

try:
free_bytes = shutil.disk_usage(Path.cwd()).free
except Exception:
free_bytes = None
if not json_output:
try:
free_bytes = shutil.disk_usage(Path.cwd()).free
except Exception:
free_bytes = None
extra = f", free={free_bytes / (1024 ** 3):.2f} GiB" if free_bytes is not None else ""
ui.console.print(
f"[dim]Disk estimate: projected={projected / (1024 ** 3):.2f} GiB, limit={args.max_disk:.2f} GiB{extra}[/dim]"
)
preflight_disk_requirement(projected_bytes=projected, limit_gib=args.max_disk, ui=ui)
limit = f", limit={max_disk:.2f} GiB" if max_disk is not None else ""
ui.console.print(f"[dim]Disk estimate: projected={projected / (1024 ** 3):.2f} GiB{limit}{extra}[/dim]")
if max_disk is not None:
from ..util import preflight_disk_requirement

preflight_disk_requirement(projected_bytes=projected, limit_gib=max_disk, ui=ui)
if download_attachments and env.drive is None:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Use explicit max_disk checks and probe the output filesystem.

Lines 83 and 124 treat 0.0 as “unset”, so --max-disk 0 silently skips the new preflight/JSON fields. Line 86 also measures free space on Path.cwd() instead of the render destination, which makes diskFreeBytes wrong when --out is on another volume.

Proposed fix
-    if disk_estimate or max_disk:
+    disk_check_requested = disk_estimate or max_disk is not None
+    if disk_check_requested:
         projected = len(inputs) * 5 * 1024 * 1024  # rough 5MiB per file heuristic
         try:
-            free_bytes = shutil.disk_usage(Path.cwd()).free
-        except Exception:
+            probe_path = output
+            while not probe_path.exists() and probe_path != probe_path.parent:
+                probe_path = probe_path.parent
+            free_bytes = shutil.disk_usage(probe_path).free
+        except OSError:
             free_bytes = None
@@
-        if disk_estimate or max_disk:
+        if disk_check_requested:
             payload["diskEstimateBytes"] = projected
             if free_bytes is not None:
                 payload["diskFreeBytes"] = int(free_bytes)

Also applies to: 124-129

🧰 Tools
🪛 Ruff (0.15.9)

[warning] 87-87: Do not catch blind exception: Exception

(BLE001)

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/cli/render.py` around lines 81 - 97, The code treats max_disk
falsily so 0.0 is ignored and also measures free space on Path.cwd() instead of
the render destination; change the boolean checks to explicit None checks (use
"if disk_estimate or max_disk is not None" and later "if max_disk is not None")
so --max-disk 0.0 is honored, and compute free_bytes by calling
shutil.disk_usage on the resolved render destination path (use the output path
variable, e.g. args.out or the function's out/output variable, falling back to
Path.cwd() if unset) instead of Path.cwd(), then pass free_bytes and max_disk
(including zero) into the UI/json output and to
preflight_disk_requirement(projected_bytes=projected, limit_gib=max_disk,
ui=ui).

Comment thread polylogue/cli/sync.py
Comment on lines +175 to +208
if rel_path is None:
meta = drive.attachment_meta(att_id)
filename = None
if isinstance(meta, dict):
raw_name = meta.get("name")
if isinstance(raw_name, str) and raw_name.strip():
filename = sanitize_filename(raw_name)
if not filename:
filename = sanitize_filename(att_id)
rel_path = str(Path("attachments") / filename)

target_path = (convo_dir / rel_path).resolve()
attempted += 1
if target_path.exists() and not force:
skipped += 1
continue

if dry_run:
ui.console.print(f"[yellow][dry-run] Would download attachment {att_id} → {target_path}[/yellow]")
downloaded += 1
continue

meta = drive.attachment_meta(att_id)
ok = drive.download_attachment(att_id, target_path)
if not ok:
err = snapshot_drive_metrics(reset=False).get("lastError")
failure = {"id": entry.get("id"), "slug": slug, "attachment": att_id, "path": str(target_path)}
if isinstance(err, str) and err.strip():
failure["error"] = err.strip()
failures.append(failure)
continue
downloaded += 1
if isinstance(meta, dict):
drive.touch_mtime(target_path, meta.get("modifiedTime"))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Duplicate drive.attachment_meta() call when rel_path is None.

When rel_path is None, attachment_meta(att_id) is called at line 176 to derive the filename, and then called again at line 197 before downloading. This is an unnecessary API call that adds latency and could be rate-limited.

🐛 Proposed fix
             if rel_path is None:
                 meta = drive.attachment_meta(att_id)
                 filename = None
                 if isinstance(meta, dict):
                     raw_name = meta.get("name")
                     if isinstance(raw_name, str) and raw_name.strip():
                         filename = sanitize_filename(raw_name)
                 if not filename:
                     filename = sanitize_filename(att_id)
                 rel_path = str(Path("attachments") / filename)
+            else:
+                meta = None

             target_path = (convo_dir / rel_path).resolve()
             attempted += 1
             if target_path.exists() and not force:
                 skipped += 1
                 continue

             if dry_run:
                 ui.console.print(f"[yellow][dry-run] Would download attachment {att_id} → {target_path}[/yellow]")
                 downloaded += 1
                 continue

-            meta = drive.attachment_meta(att_id)
+            if meta is None:
+                meta = drive.attachment_meta(att_id)
             ok = drive.download_attachment(att_id, target_path)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/cli/sync.py` around lines 175 - 208, When rel_path is None the code
calls drive.attachment_meta(att_id) twice; to fix, cache and reuse the metadata:
when rel_path is None, call meta = drive.attachment_meta(att_id) once, derive
filename/rel_path from meta and keep that meta for later touch_mtime; when
rel_path is not None, DO NOT call attachment_meta up-front — instead call meta =
drive.attachment_meta(att_id) only after a successful
drive.download_attachment(att_id, target_path) if you need it for
drive.touch_mtime(target_path, meta.get("modifiedTime")). Update the logic
around rel_path, meta, drive.download_attachment and drive.touch_mtime so
attachment_meta is invoked at most once per attachment.

Comment thread polylogue/cli/timeline.py
theme = getattr(args, "theme", "light") or "light"
open_result = bool(getattr(args, "open", False))

rows = _load_rows(limit=limit, providers=providers)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Query the archive DB selected by env, not the process default.

run_timeline_cli() receives env, but _load_rows() always uses open_connection(None). In tests or multi-archive setups this will read the wrong database and make browse timeline ignore the injected CommandEnv.

💡 Suggested fix
-    rows = _load_rows(limit=limit, providers=providers)
+    rows = _load_rows(
+        limit=limit,
+        providers=providers,
+        db_path=env.database.resolve_path(),
+    )
@@
-def _load_rows(*, limit: int, providers: Optional[set[str]]) -> List[TimelineRow]:
-    with open_connection(None) as conn:
+def _load_rows(*, limit: int, providers: Optional[set[str]], db_path: Path | None) -> List[TimelineRow]:
+    with open_connection(db_path) as conn:

Also applies to: 200-201

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/cli/timeline.py` at line 153, run_timeline_cli is passing an env
but _load_rows always calls open_connection(None), so the archive DB selected by
env is ignored; update the calls to _load_rows in run_timeline_cli (and the
other call sites noted) to accept and forward the CommandEnv (e.g., pass env)
and modify _load_rows to call open_connection(env) instead of
open_connection(None) so the function opens the DB for the provided env; ensure
function signature changes (and any callers) and that any tests/multi-archive
usage now use the injected env when resolving providers.

Comment thread polylogue/commands.py
Comment on lines +715 to +718
def _maybe_plain_progress(done: int, total: int) -> None:
nonlocal last_progress_time
if not env.ui.plain or total <= 0:
return

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Don't rely on ui.plain being part of the fallback UI contract.

CommandEnv._ensure_ui_contract() only backfills summary and progress. Reading env.ui.plain directly here means lightweight test/integration UIs that used to work with CommandEnv now fail with AttributeError as soon as sync starts.

💡 Suggested fix
-        if not env.ui.plain or total <= 0:
+        if not getattr(env.ui, "plain", False) or total <= 0:
             return
📝 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.

Suggested change
def _maybe_plain_progress(done: int, total: int) -> None:
nonlocal last_progress_time
if not env.ui.plain or total <= 0:
return
def _maybe_plain_progress(done: int, total: int) -> None:
nonlocal last_progress_time
if not getattr(env.ui, "plain", False) or total <= 0:
return
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/commands.py` around lines 715 - 718, The code in
_maybe_plain_progress reads env.ui.plain which isn't guaranteed by
CommandEnv._ensure_ui_contract(), causing AttributeError for lightweight UIs;
change the guard to use a safe attribute check like getattr(env.ui, "plain",
False) (or hasattr(env.ui, "plain") and default to False) so the function
returns early when plain isn't present or total <= 0. Update the conditional in
_maybe_plain_progress to use getattr(env.ui, "plain", False) (and keep the total
<= 0 check) to avoid relying on env.ui.plain being part of the fallback UI
contract.

Comment on lines +72 to +90
def test_golden_chatgpt_tool(tmp_path, state_env, monkeypatch):
monkeypatch.setenv("POLYLOGUE_FIXED_NOW", FIXED_NOW)
fixtures = _repo_root() / "tests" / "fixtures" / "golden"
golden_dir = _repo_root() / "tests" / "golden"
out_dir = tmp_path / "out"

results = import_chatgpt_export(
_rel(fixtures / "chatgpt_tool"),
output_dir=out_dir,
collapse_threshold=10,
html=False,
html_theme="light",
force=True,
)
assert results
slug = results[0].slug
db_path = Path(state_env) / "polylogue.db"
_render_slug(db_path, out_dir, slug)
_assert_golden(out_dir / slug / "conversation.md", golden_dir / "chatgpt-tool.md")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

Consider parametrizing the new tool snapshot tests.

Both tests share the same structure and differ only by importer/fixture/golden target. A parametrized test would reduce duplication and future update cost.

Also applies to: 113-131

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/test_golden_snapshots.py` around lines 72 - 90, These two
nearly-identical tests (e.g., test_golden_chatgpt_tool) should be combined into
a parametrized pytest to avoid duplication: replace the separate functions with
a single test function decorated with pytest.mark.parametrize that yields tuples
of (fixture_subdir, importer_fn or import parameters, golden_filename) and then
call import_chatgpt_export (or the appropriate importer) with the parametrized
inputs, compute slug and db_path the same way, call _render_slug, and assert
with _assert_golden using the parametrized golden target; ensure the new param
set covers both existing cases referenced around lines 72–90 and 113–131 so only
the fixture/golden values change per parameter.

Comment thread tests/test_html.py
Comment on lines +56 to +63
local_img = tmp_path / "attachments" / "image.png"
local_img.parent.mkdir(parents=True, exist_ok=True)
local_img.write_bytes(b"\x89PNG\r\n\x1a\n")
doc = MarkdownDocument(
body="Just text",
metadata={"title": "Safe"},
attachments=[AttachmentInfo(name="image.png", link="http://example.com/remote", local_path=local_img, size_bytes=9, remote=False)],
stats={},

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Keep attachment fixture metadata consistent with file bytes.

Line 58 writes an 8-byte payload, but Line 62 sets size_bytes=9. This can mask size-formatting regressions in renderer behavior.

Suggested fix
-    local_img.write_bytes(b"\x89PNG\r\n\x1a\n")
+    png_bytes = b"\x89PNG\r\n\x1a\n"
+    local_img.write_bytes(png_bytes)
@@
-        attachments=[AttachmentInfo(name="image.png", link="http://example.com/remote", local_path=local_img, size_bytes=9, remote=False)],
+        attachments=[AttachmentInfo(name="image.png", link="http://example.com/remote", local_path=local_img, size_bytes=len(png_bytes), remote=False)],
📝 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.

Suggested change
local_img = tmp_path / "attachments" / "image.png"
local_img.parent.mkdir(parents=True, exist_ok=True)
local_img.write_bytes(b"\x89PNG\r\n\x1a\n")
doc = MarkdownDocument(
body="Just text",
metadata={"title": "Safe"},
attachments=[AttachmentInfo(name="image.png", link="http://example.com/remote", local_path=local_img, size_bytes=9, remote=False)],
stats={},
local_img = tmp_path / "attachments" / "image.png"
local_img.parent.mkdir(parents=True, exist_ok=True)
png_bytes = b"\x89PNG\r\n\x1a\n"
local_img.write_bytes(png_bytes)
doc = MarkdownDocument(
body="Just text",
metadata={"title": "Safe"},
attachments=[AttachmentInfo(name="image.png", link="http://example.com/remote", local_path=local_img, size_bytes=len(png_bytes), remote=False)],
stats={},
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/test_html.py` around lines 56 - 63, The test's attachment fixture is
inconsistent: local_img.write_bytes(b"\x89PNG\r\n\x1a\n") writes 8 bytes but
AttachmentInfo is created with size_bytes=9; update the fixture so size_bytes
matches the actual written bytes (e.g., set size_bytes=8) or change the written
payload to match 9 bytes; locate the AttachmentInfo construction in
tests/test_html.py (symbols: local_img, AttachmentInfo, size_bytes) and make the
size_bytes value equal to the actual byte length.

Comment on lines +115 to +179
def test_import_chatgpt_export_skips_when_unchanged(tmp_path):
export_dir = tmp_path / "chatgpt_skip"
export_dir.mkdir()
conversations = [
{
"id": "conv-skip",
"title": "Skip Chat",
"create_time": 1,
"update_time": 2,
"mapping": {
"node-user": {
"id": "node-user",
"message": {
"id": "msg-user",
"author": {"role": "user"},
"create_time": 1,
"content": {"content_type": "text", "parts": ["Hello"]},
},
},
"node-assistant": {
"id": "node-assistant",
"message": {
"id": "msg-assistant",
"author": {"role": "assistant"},
"create_time": 2,
"content": {"content_type": "text", "parts": ["Hi there"]},
},
},
},
}
]
_write(export_dir / "conversations.json", conversations)

out_dir = tmp_path / "out"
first = import_chatgpt_export(
export_dir,
output_dir=out_dir,
collapse_threshold=10,
html=False,
html_theme="light",
force=False,
)
assert first and not first[0].skipped

second = import_chatgpt_export(
export_dir,
output_dir=out_dir,
collapse_threshold=10,
html=False,
html_theme="light",
force=False,
)
assert second and second[0].skipped
assert second[0].skip_reason

third = import_chatgpt_export(
export_dir,
output_dir=out_dir,
collapse_threshold=10,
html=True,
html_theme="light",
force=False,
)
assert third and not third[0].skipped

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

Add one regression check for missing-output skip gating.

These tests cover hash/config changes well, but they don’t assert the documented precondition that unchanged imports should only skip when expected outputs already exist. Add a case that removes markdown_path (or output dir) and verifies a subsequent run is not skipped.

Also applies to: 219-267

🧰 Tools
🪛 Ruff (0.15.9)

[warning] 157-157: Assertion should be broken down into multiple parts

Break down assertion into multiple parts

(PT018)


[warning] 167-167: Assertion should be broken down into multiple parts

Break down assertion into multiple parts

(PT018)


[warning] 178-178: 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 115 - 179, Update the
test_import_chatgpt_export_skips_when_unchanged test to assert that skipping
only happens when expected outputs exist by adding a step that removes the
generated output (e.g., delete the markdown/html file or the entire
out_dir/markdown_path created by the first run) before calling
import_chatgpt_export a third time; call import_chatgpt_export (function name)
after removing the output and assert the result is not skipped (use the same
collapse_threshold/html/html_theme/force arguments as in the other calls) so the
test verifies that absence of the expected output prevents the "skipped" path.

Comment thread tests/test_search_open.py

_open_single_search_hit(ui, hit)

assert opened and opened[0].endswith("#msg-2")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

Split the compound assertion for clearer failures.

assert opened and opened[0].endswith("#msg-2") makes failures less diagnosable. Prefer two asserts so emptiness vs bad anchor is explicit.

Suggested tweak
-    assert opened and opened[0].endswith("#msg-2")
+    assert opened
+    assert opened[0].endswith("#msg-2")
🧰 Tools
🪛 Ruff (0.15.9)

[warning] 77-77: 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_search_open.py` at line 77, The compound assertion using the
opened variable should be split into two explicit checks: replace the single
assertion that combines existence and content with first asserting that opened
is truthy (e.g., assert opened) and then asserting the anchor of the first
element (e.g., assert opened[0].endswith("#msg-2")); update the assertion in the
test (around the opened variable in tests/test_search_open.py) to these two
separate asserts so failures clearly indicate emptiness vs wrong anchor.

Comment thread tests/test_search_open.py
Comment on lines +103 to +104
hit = _hit_for_path(Path("/tmp/conversation.md"))
args = SimpleNamespace(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Avoid hardcoded /tmp path in test data.

Using Path("/tmp/conversation.md") is platform-specific and also triggers Ruff S108. Use tmp_path to keep the test portable and lint-clean.

Portable fix
-def test_search_csv_stdout(monkeypatch, capsys) -> None:
-    hit = _hit_for_path(Path("/tmp/conversation.md"))
+def test_search_csv_stdout(monkeypatch, capsys, tmp_path: Path) -> None:
+    hit = _hit_for_path(tmp_path / "conversation.md")
📝 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.

Suggested change
hit = _hit_for_path(Path("/tmp/conversation.md"))
args = SimpleNamespace(
def test_search_csv_stdout(monkeypatch, capsys, tmp_path: Path) -> None:
hit = _hit_for_path(tmp_path / "conversation.md")
args = SimpleNamespace(
🧰 Tools
🪛 Ruff (0.15.9)

[error] 103-103: Probable insecure usage of temporary file or directory: "/tmp/conversation.md"

(S108)

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/test_search_open.py` around lines 103 - 104, The test uses a hardcoded
Path("/tmp/conversation.md") which is platform-specific and triggers Ruff S108;
update the test to use the pytest tmp_path fixture instead (e.g., create a Path
via tmp_path / "conversation.md") and pass that to _hit_for_path so the hit
variable is created from a temp-file path; also ensure the test function
signature includes the tmp_path parameter and that any SimpleNamespace setup
that depends on this path uses the tmp_path-derived Path.

@Sinity Sinity closed this Apr 9, 2026
@Sinity Sinity added the faux-pull-request PR created as part of a history rewrite process label Apr 9, 2026
@Sinity
Sinity deleted the feature/test/attachment-coverage-and-golden-fixtures branch April 9, 2026 23:02
Sinity added a commit that referenced this pull request Apr 22, 2026
…arness (#42)

Extend the test suite to cover attachment failure recovery, incremental
import skip logic, and interactive CLI flows. Production code changes
make these scenarios testable and add two browse subcommands.

Attachment failure recovery (pipeline.py, commands.py, cli/sync.py):
- Replace hard RuntimeError on download failure with AttachmentDownloadError
  that carries partial results (per_index_links, attachments, failed_items)
- RenderDocumentStage catches AttachmentDownloadError, continues with
  partial attachments, and records failures in pipeline context
- sync_command aggregates per-conversation attachment failures into run
  payload as failedAttachments list with per-item id/filename/path/error
- New --attachments-only flag retries just failed Drive attachments from
  a previous run without re-rendering conversations
- _apply_resume_from() parses failedAttachments alongside failedChats

Import skip optimization (importers/chatgpt.py, importers/claude_ai.py):
- Compute render config hash from collapse/html/theme/ocr/sanitize params
- Skip re-import when raw content hash, render config hash, and output
  files are all unchanged; --force overrides
- Track sync state via set_import_sync_state() keyed by provider+conv_id

HTML viewer (html.py):
- Image lightbox with Esc-close, click-outside-dismiss, and open-in-tab
- Attachment cards show type icon, thumbnail preview, and filter input
- Responsive layout collapses sidebar below 860px breakpoint
- TOC link text strips dynamically-added anchor buttons via cloneNode
- _anchorize() strips HTML tags before generating anchor IDs

Browse commands (cli/analytics.py, cli/timeline.py):
- analytics: provider/model/role/branch-hotspot aggregates from SQLite
- timeline: sortable conversation list with token/word/attachment stats
- Both emit JSON (--json) or themed HTML with client-side filtering

Content hash stability (document_store.py):
- Strip path-dependent metadata keys (outputPath, htmlPath, sessionPath,
  sourceExportPath, bundle_path, export_root) from hash computation so
  content hashes are stable across machines and archive locations

Tests:
- Golden tool+attachment fixtures for ChatGPT and Claude providers
- Interactive PTY harness using pexpect with stub gum/sk/bat/delta
- Attachment failure tracking without pipeline abort
- Attachment retry-only flow with stub Drive client
- Import skip on unchanged raw+render config for both providers
- Watch stall detection before debounce skip
- Search CSV output, browser/editor open dispatch
- Analytics and timeline CLI JSON output paths

Bug fixes:
- cli/sync.py: fix JSON output block indentation (was nested inside
  except clause, making it unreachable on success)
- cli/watch.py: evaluate stall timeout before debounce skip so
  --fail-on-stall fires even during rapid event bursts; reset stalled
  flag after successful sync to avoid duplicate warnings
- Disk estimate logic extracted to standalone --disk-estimate flag
  independent of --max-disk
Sinity added a commit that referenced this pull request Jul 31, 2026
## Summary

- Extracts the hand-duplicated
`_MockServer`/`_MockHeaders`/`_make_handler` trio from three daemon test
files into a shared `tests/infra/daemon_http_harness.py`
(polylogue-myhg).
- Closes three CodeRabbit findings from PR #3425's review that were
triaged and filed as polylogue-2vor rather than blocking that merge (all
three are in `polylogue/insights/session_commit.py`, with regression
tests).

## Problem

**polylogue-myhg**: CodeRabbit flagged (PR #2559) that
`_MockServer`/`_MockHeaders`/`_make_handler` were duplicated
near-identically across `test_daemon_http_security.py`,
`test_daemon_events_endpoint.py`, and `test_provider_usage_endpoint.py`.
Drift already happened once: the `host=` parameter was added to two of
the three copies during a fast-follow, not all three. A fresh grep
tonight confirmed the duplication was still live.

**polylogue-2vor**: three P2 findings in `session_commit.py` were left
unaddressed at PR #3425's merge time:
1. `typed_refs_from_session_refs()` coerced a `session_refs` row with a
valid `url`/`repo` but no `ref_number` to "PR #0" (observed for Codex
Cloud's `chatgpt_codex_sidecar._pull_request_ref()`, which stores
`external_pull_request_id` in `url` and leaves `repo`/`number` unset).
Since typed refs are authoritative over the regex fallback, this could
suppress a correctly-parsed regex result with a bogus PR #0.
2. Disagreement detection compared PR/issue identity by bare number
only, so `acme/product#42` and `other/repo#42` compared equal — a real
cross-repo disagreement was never surfaced.
3. Foreign-trailer classification flagged a disagreement whenever a
commit carried *any* Claude-Session trailer, even when the current
session has no `bridge_session_ids` of its own — i.e. even with no typed
identity to compare against.

## Solution

**Mock harness extraction** (`tests/infra/daemon_http_harness.py`):
- `MockDaemonServer`, `MockHeaders`, `make_daemon_handler`,
`capture_json_response`, `capture_responses` — these mock only the HTTP
transport boundary (the listening socket/`ThreadingHTTPServer` a real
`DaemonAPIHandler` normally sits on, and the parsed header block a
socket read would produce). `do_GET`/`do_POST` dispatch, `_check_auth`,
cross-origin checks, route handlers, and JSON/SSE serialization all
still run as the real production `DaemonAPIHandler` built via `__new__`
— no boundary that was previously mocked is hollowed out.
- The three named test files now import the shared harness instead of
defining their own copies. `test_daemon_http_security.py` keeps a thin
file-local `_make_handler` wrapper because that file's whole point is
exercising the auth-required path, so its default server needs a
configured token (`"secret"`) unlike the harness's own open-by-default
`MockDaemonServer`.
- While touching `test_daemon_events_endpoint.py`, three ad-hoc
`type()`-built `_Srv` server stand-ins were also converted to
`MockDaemonServer` — same duplication pattern CodeRabbit flagged in the
original trio.
- Fixed two cross-file importers (`test_web_auth.py`,
`test_route_contracts.py`) that imported
`_MockServer`/`_capture_responses` *from* `test_daemon_http_security.py`
rather than defining their own copies — a case a narrow per-file
`devtools test` run doesn't catch but whole-repo `mypy --strict` does.

**session_commit.py fixes** (regression test per finding, see
`tests/unit/insights/test_session_commit.py`):
1. `typed_refs_from_session_refs()` now tries to recover a real number
by parsing a genuine `github.com` PR/issue URL out of `url` when
`number` is absent; if that also fails, the row is skipped rather than
defaulting to 0.
2. New `_refs_match()` compares the full `(owner, repo, number)`
identity whenever both refs are repo-qualified, falling back to
number-only equality when either side lacks repo identity (e.g. a bare
`#42` regex mention).
3. `foreign_trailer` now additionally requires `own_trailer_tokens` to
be non-empty.

## Verification

- `ruff check` + `mypy` (strict, whole repo: 2397 source files) clean.
- `devtools test tests/unit/daemon/test_daemon_http_security.py
tests/unit/daemon/test_daemon_events_endpoint.py
tests/unit/daemon/test_provider_usage_endpoint.py
tests/unit/daemon/test_web_auth.py
tests/unit/daemon/test_route_contracts.py` → 709 passed.
- `devtools test tests/unit/insights/test_session_commit.py` → 46
passed; also ran `tests/unit/cli/test_correlate_view.py
tests/unit/storage/test_archive_tiers_write.py` (other consumers of
`session_commit.py`) → 80 passed.
- `devtools verify --quick` → clean end to end.

Ref polylogue-myhg
Ref polylogue-2vor

---------

Co-authored-by: Claude <[email protected]>
@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

Only the rows listed above are dispositioned. Held findings remain open.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:cli CLI area:parser Parser area:pipeline Pipeline area:qa QA area:storage Storage faux-pull-request PR created as part of a history rewrite process type:test Tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants