Skip to content

feat: add automation, persistence layer, and NixOS module - #10

Closed
Sinity wants to merge 2 commits into
masterfrom
feature/feat/automation-persistence-nixos
Closed

Sinity wants to merge 2 commits into
masterfrom
feature/feat/automation-persistence-nixos

Conversation

@Sinity

@Sinity Sinity commented Apr 7, 2026 •

Copy link
Copy Markdown
Owner

Summary

Adds the infrastructure needed for Polylogue to run unattended: a document persistence layer that makes reruns idempotent, file watchers for continuous sync, systemd/cron snippet generation from a shared target registry, and a NixOS module that wires everything into declarative timers. Every successful write now also updates a local SQLite FTS index so downstream tooling can query metadata without reparsing Markdown.

Motivation

Up to this point, every polylogue import or polylogue sync run rewrites all output files unconditionally. That means:

  • Cron jobs waste IO rewriting identical files, and git repos accumulate no-op diffs
  • Users who hand-edit rendered Markdown lose their changes silently on the next run
  • There's no single place to check whether a conversation has already been processed
  • Setting up unattended sync requires manually writing systemd units or cron entries, duplicating CLI flag knowledge

The persistence layer solves the first three problems; the automation framework and NixOS module solve the fourth.

I considered adding skip logic directly in each importer, but the duplication was already bad — four importers plus render and sync all had near-identical write-then-optionally-HTML-then-optionally-diff sequences. Extracting persist_document() as a shared function was the natural consolidation point, and it gave a clean place to hang content hashing, dirty detection, and index updates.

Document persistence (document_store.py)

The core abstraction is persist_document(), which every importer and both render/sync commands call instead of writing files directly. It:

  1. Computes a SHA-256 content hash of the document body
  2. Checks state.json for a matching (provider, conversation_id) entry
  3. Skips the write if the stored hash, collapse threshold, attachment policy, and HTML flag all match — returns a DocumentPersistenceResult with skipped=True
  4. Detects dirty-local state: if the on-disk body hash doesn't match the stored hash, the file was manually edited; the importer preserves the local content, marks dirty=True in both state and front matter, and skips
  5. On write: stamps a polylogue: front matter block, writes Markdown + optional HTML, updates conversation state, and calls update_index()

The dirty-local path deserves a code snippet because the logic is non-obvious:

# If the user edited the file locally (body_hash != stored contentHash)
# AND the remote content hasn't changed, preserve local edits
if remote_same and existing:
    dirty_meta = _ensure_polylogue_metadata(existing.metadata)
    polylogue = dirty_meta.get("polylogue", {})
    polylogue["dirty"] = True
    polylogue["localHash"] = existing.body_hash
    _write_markdown(markdown_path, dirty_meta, existing.body)  # keeps their edits
    return DocumentPersistenceResult(skipped=True, skip_reason="dirty-local", ...)

Automation framework

automation_targets.json defines five targets with their CLI commands and default arguments:

{
  "codex": {
    "name": "polylogue-sync-codex",
    "command": ["sync-codex", "--plain", "--json"],
    "defaults": { "collapseThreshold": 24, "html": false }
  },
  ...
}

automation.py reads this registry and exposes systemd_snippet() and cron_snippet() that merge target defaults with user overrides to produce ready-to-paste scheduler entries. The CLI surfaces these as polylogue automation systemd --target codex --interval 10m.

The NixOS module (nix/modules/polylogue.nix) reads the same JSON at Nix eval time, validates target names, and generates systemd service/timer pairs. Users get:

services.polylogue = {
  enable = true;
  targets.codex = { enable = true; timer.interval = "10m"; };
  targets."claude-code".enable = true;
};

File watchers

polylogue watch codex and polylogue watch claude-code use the watchfiles library to monitor session directories. Changes are debounced (default 2s), and only .jsonl file changes trigger a sync. --once runs a single sync pass and exits, useful for testing.

Watch runs log to the same runs.json telemetry as scheduled runs, so polylogue status --json --watch can monitor both watchers and cron jobs from a single dashboard.

Indexing

Every persist_document() call fires update_index(), which dispatches to the configured backend:

  • sqlite (default): maintains a conversations table with content hash, token count, and dirty flag, plus an FTS5 virtual table for full-text search
  • qdrant: upserts into a Qdrant collection (requires POLYLOGUE_QDRANT_URL)
  • none: no-op

The SQLite path is lightweight enough to run on every write without noticeable overhead.

Packaging

  • Added pyproject.toml with polylogue console_scripts entry point
  • Rewrote flake.nix to use buildPythonApplication and export packages, apps, devShells.ci, and nixosModules
  • Added pyperclip and watchfiles to the dev shell

Changes grouped by concern

Importers: All four importers (chatgpt, claude_ai, claude_code, codex) call persist_document() instead of writing files directly. ImportResult gains skipped, skip_reason, dirty, and content_hash fields. The CLI summary display accounts for skipped conversations.

State management: util.py gains assign_conversation_slug() for stable provider-scoped slug allocation, conversation_is_current() for skip detection, and update_conversation_state() for per-conversation state tracking.

Status command: Gains --json, --watch, and --interval flags. A new provider-level summary aggregates stats across command types (e.g., both sync and sync-codex roll up under their respective providers). Duration tracking added to all run records.

Clipboard: --to-clipboard flag on render and all import subcommands copies single-file output. Drive credential setup checks the clipboard for an OAuth JSON payload before prompting for a file path.

Documentation: multi-provider.md deleted; content distributed into five focused docs under docs/providers/. README updated with watcher usage, automation targets, NixOS module example, and indexing configuration.

Test coverage

  • test_automation_snippets.py: systemd/cron generation, describe roundtrip, CLI dispatch
  • test_commands_logic.py: render/sync through persistence layer with SQLite index verification, skip-on-rerun behavior
  • test_importers_multi.py: repeat-import skip detection with dirty-local scenario
  • test_status.py: provider summary aggregation from run records

@Sinity Sinity added type:feat New feature area:cli CLI area:pipeline Pipeline area:storage Storage labels Apr 7, 2026
Copilot AI review requested due to automatic review settings April 7, 2026 11:29
@Sinity Sinity added type:feat New feature area:cli CLI area:pipeline Pipeline area:storage Storage labels Apr 7, 2026
@coderabbitai

coderabbitai Bot commented Apr 7, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This pull request introduces comprehensive automation, persistence, and indexing infrastructure for the Polylogue project. It adds systemd/cron scheduling, real-time local session watching, document persistence with state management, SQLite and Qdrant indexing backends, clipboard integration, and corresponding CLI commands and NixOS module support.

Changes

Cohort / File(s) Summary
Documentation
README.md
Extended with new sections covering watch commands (polylogue watch codex/claude-code), status monitoring (--json, --watch, --interval), clipboard output (--to-clipboard), automation infrastructure (polylogue automation describe/systemd/cron), Nix flake usage, and indexing backend configuration.
Nix Infrastructure
flake.nix
Restructured to add packages.default/polylogue exposing a packaged Python application, apps.default/polylogue CLI entry points, new devShells.ci for CI workflows, replaced checks.default with package derivation, and added nixosModules.default/polylogue for declarative automation.
Nix Configuration
nix/devshell.nix, nix/modules/polylogue.nix
Added pyperclip and watchfiles Python dependencies; introduced new NixOS module defining services.polylogue with configurable targets, timers, environment variables, and directory management for systemd-based automation.
Automation System
polylogue/automation.py, polylogue/automation_targets.json
New automation module providing target registry, CLI snippet generators (systemd/cron), argument merging logic, and JSON configuration defining five automation targets (codex, claude-code, drive-sync, gemini-render, chatgpt-import) with defaults.
Document Persistence
polylogue/document_store.py
New module handling markdown output persistence, front-matter parsing/emission, conversation state tracking, dirty-content reconciliation, skip detection, HTML generation, and index updates via centralized persist_document function.
Indexing Infrastructure
polylogue/index.py, polylogue/index_sqlite.py, polylogue/index_qdrant.py
New indexing layer supporting backend selection via POLYLOGUE_INDEX_BACKEND. SQLite backend persists conversation metadata and FTS indexes; Qdrant backend stores vector embeddings and payloads with environment-based configuration.
CLI and Commands
polylogue/cli.py, polylogue/commands.py
Extended CLI with watch command family (codex/claude-code with --debounce, --once), automation command family (systemd/cron/describe generators), status --watch/--json/--interval streaming, and --to-clipboard on import/render. Refactored command handlers to use centralized persist_document and added provider-level aggregation in status reporting.
Importers
polylogue/importers/base.py, polylogue/importers/chatgpt.py, polylogue/importers/claude_ai.py, polylogue/importers/claude_code.py, polylogue/importers/codex.py
Updated ImportResult dataclass to support optional documents and skip tracking. Refactored all importers to delegate persistence to persist_document, use conversation slug assignment, and handle skip/dirty states consistently.
Utilities
polylogue/util.py, polylogue/drive_client.py, polylogue/local_sync.py, polylogue/options.py
Added clipboard support (read_clipboard_text, write_clipboard_text), conversation state management (get_conversation_state, assign_conversation_slug, update_conversation_state, conversation_is_current), and credential acquisition from clipboard in Drive client. Extended StatusOptions and LocalSyncResult with watch/interval and duration fields.
Package Configuration
pyproject.toml
New project metadata with runtime dependencies for API clients, OAuth, async IO, templating, markdown, clipboard, and file watching; console script entry point and package data configuration.
Tests
tests/test_automation_snippets.py, tests/test_commands_logic.py, tests/test_importers_multi.py, tests/test_status.py
New test suite covering automation snippet generation, end-to-end command/index persistence flows, importer skip behavior with dirty-content detection, and provider-level status aggregation.

Sequence Diagram(s)

sequenceDiagram
    actor User
    participant CLI as CLI (watch/sync)
    participant LocalSync as LocalSync Engine
    participant Importer as Importer
    participant PersistDoc as Document Store
    participant ConvState as Conversation State
    participant Index as Index Backend
    participant Filesystem as Filesystem

    User->>CLI: polylogue watch codex
    CLI->>LocalSync: _sync_sessions()
    
    loop Until debounce timeout or --once
        LocalSync->>Importer: import_fn()
        Importer->>PersistDoc: persist_document()
        
        PersistDoc->>ConvState: get_conversation_state()
        ConvState-->>PersistDoc: Load existing metadata
        
        PersistDoc->>ConvState: assign_conversation_slug()
        ConvState->>Filesystem: Update state.json
        
        PersistDoc->>PersistDoc: Build markdown + frontmatter
        PersistDoc->>Filesystem: Write .md file
        
        alt HTML enabled
            PersistDoc->>Filesystem: Write .html file
        end
        
        PersistDoc->>ConvState: update_conversation_state()
        ConvState->>Filesystem: Persist conversation metadata
        
        PersistDoc->>Index: update_index()
        Index->>Filesystem: Update SQLite FTS or Qdrant
        
        PersistDoc-->>Importer: DocumentPersistenceResult
        Importer-->>LocalSync: ImportResult
        
        LocalSync->>LocalSync: Compute diffs, log results
    end
    
    LocalSync-->>CLI: LocalSyncResult
    CLI->>User: Display sync summary
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Poem

🐰 Hops through the code with glee

Watch the sessions dance in real time,
Persist each conversation, organized and sublime,
Index them swift in SQLite's glow,
Automate with systemd, let the syncs flow,
Clipboard magic, NixOS charm—
A rabbit's refactor keeps the codebase warm! ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 1.00% 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 The title accurately summarizes the main changes: adding automation infrastructure, a persistence layer for documents, and a NixOS module for declarative configuration.
Description check ✅ Passed The PR description is comprehensive, well-structured, and follows the template closely with all required sections present and detailed.

✏️ 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/feat/automation-persistence-nixos

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

Sinity added a commit that referenced this pull request Apr 7, 2026
… module (#10)

Introduce infrastructure for unattended operation: a persistence layer
that deduplicates writes across reruns, file watchers for continuous
sync, systemd/cron snippet generation, and a NixOS module that wires
it all into declarative timers.

Document persistence (polylogue/document_store.py):
- persist_document() centralizes Markdown/HTML write logic previously
  duplicated across every importer and both render/sync commands
- Content-hash comparison skips unchanged conversations on rerun
- Dirty-local detection: when the on-disk body diverges from the stored
  hash, the importer preserves local edits and marks the entry dirty
  rather than overwriting
- Front matter gains a `polylogue:` metadata block tracking slug,
  provider, contentHash, collapseThreshold, attachmentPolicy, and
  dirty state
- All four importers (chatgpt, claude_ai, claude_code, codex) and
  both render_command/sync_command now route through persist_document()

Automation targets (polylogue/automation.py, automation_targets.json):
- JSON registry defines five targets (codex, claude-code, drive-sync,
  gemini-render, chatgpt-import) with per-target default args
- systemd_snippet() and cron_snippet() generate ready-to-use scheduler
  entries with merged defaults and user overrides
- CLI gains `polylogue automation systemd|cron|describe` subcommands

File watchers (polylogue/cli.py):
- `polylogue watch codex` and `polylogue watch claude-code` use
  watchfiles to trigger sync on JSONL changes with configurable
  debounce; `--once` runs a single pass and exits
- Watch runs log to the same telemetry as scheduled runs

Indexing backends (polylogue/index.py, index_sqlite.py, index_qdrant.py):
- Every persist_document() call updates a SQLite FTS5 index by default
- POLYLOGUE_INDEX_BACKEND env var selects sqlite, qdrant, or none
- SQLite schema: conversations table with content_hash, tokens, dirty
  columns plus an FTS5 virtual table for full-text search

NixOS module (nix/modules/polylogue.nix):
- Declarative services.polylogue option tree with per-target enable,
  outputDir, timer interval/bootDelay, collapseThreshold, html, and
  environment overrides
- Reads automation_targets.json at eval time to validate target names
  and wire default commands into systemd service ExecStart lines
- tmpfiles rules ensure working/output/state directories exist

Nix packaging (flake.nix, pyproject.toml):
- pyproject.toml defines build metadata, dependencies, and the
  polylogue console_scripts entry point
- flake.nix replaces inline check with buildPythonApplication, exports
  packages, apps, devShells.ci, and nixosModules outputs
- devshell gains pyperclip and watchfiles

State and CLI enhancements:
- util.py: assign_conversation_slug() allocates stable provider-scoped
  slugs; conversation_is_current() drives skip logic;
  read_clipboard_text()/write_clipboard_text() wrap pyperclip
- status command gains --json, --watch, --interval flags and a
  provider-level summary that aggregates across command types
- ImportResult grows skipped/skip_reason/dirty/content_hash fields;
  summarize_import() accounts for skipped conversations
- --to-clipboard flag on render and all import subcommands

Documentation:
- multi-provider.md deleted; content split into five per-provider
  docs under docs/providers/ (chatgpt, claude-ai, claude-code,
  gemini, openai-codex)
- README updated with watcher usage, automation targets, NixOS
  module example, and indexing backend configuration

@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

diff=diff_enabled,

P1 Badge Define diff flag before calling Claude Code sync

run_sync_claude_code() passes diff=diff_enabled into sync_claude_code_sessions, but diff_enabled is never assigned in this function. As a result, every sync-claude-code invocation raises NameError before any sync work starts, so the command is effectively broken regardless of user input.

ℹ️ 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.py Resolved
Comment thread polylogue/automation.py Resolved

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 adds the infrastructure for unattended/continuous Polylogue operation by introducing a shared persistence layer (idempotent writes + dirty-local preservation), automation target metadata with scheduler snippet generation, local session watchers, and an always-updated search index (SQLite FTS by default), along with packaging and a NixOS module for declarative timers.

Changes:

  • Introduces persist_document() and provider-scoped conversation state helpers to make imports/render/sync idempotent and dirty-local safe.
  • Adds automation targets + CLI (polylogue automation ...) and watch commands (polylogue watch ...) with run telemetry aggregation in status.
  • Adds incremental indexing backends (SQLite FTS + optional Qdrant), plus Nix flake packaging and a NixOS module.

Reviewed changes

Copilot reviewed 26 out of 26 changed files in this pull request and generated 11 comments.

Show a summary per file
File Description
tests/test_status.py Adds provider-level status aggregation test coverage.
tests/test_importers_multi.py Adds repeat-import skip + dirty-local scenario coverage and state isolation.
tests/test_commands_logic.py Exercises render/sync via persistence + verifies SQLite index updates.
tests/test_automation_snippets.py Tests systemd/cron snippet generation, target describe, and CLI dispatch.
README.md Documents watchers, automation, status streaming, and indexing configuration.
pyproject.toml Adds Python packaging metadata and console script entry point.
polylogue/util.py Adds conversation state helpers, UTC timestamp helper, and clipboard helpers.
polylogue/options.py Extends status options/result to include JSON/watch/provider summary fields.
polylogue/local_sync.py Adds duration tracking and handles skipped persistence results.
polylogue/index.py Introduces index backend dispatcher (sqlite/qdrant/none).
polylogue/index_sqlite.py Adds SQLite schema + FTS maintenance for persisted conversations.
polylogue/index_qdrant.py Adds optional Qdrant upsert backend.
polylogue/importers/codex.py Switches Codex importer to persistence layer + stable slugs/state.
polylogue/importers/claude_code.py Switches Claude Code importer to persistence layer + stable slugs/state.
polylogue/importers/claude_ai.py Switches Claude export importer to persistence layer + stable slugs/state.
polylogue/importers/chatgpt.py Switches ChatGPT exporter importer to persistence layer + stable slugs/state.
polylogue/importers/base.py Extends ImportResult to represent skipped/dirty/hash outcomes.
polylogue/drive_client.py Adds clipboard-based credential bootstrap flow.
polylogue/document_store.py Implements persist_document() with skip/dirty-local behavior + indexing hooks.
polylogue/commands.py Routes render/sync through persistence and adds provider summary aggregation.
polylogue/cli.py Adds watch + automation subcommands, clipboard copy, and status watch/JSON output.
polylogue/automation.py Loads target registry and generates systemd/cron snippets.
polylogue/automation_targets.json Defines automation targets and default CLI flags.
nix/modules/polylogue.nix Adds NixOS module that generates per-target systemd services/timers from target metadata.
nix/devshell.nix Adds pyperclip and watchfiles to the dev shell.
flake.nix Reworks flake to build a Python application package, expose apps/devShells/checks, and export the NixOS module.

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

Comment thread polylogue/automation.py
Comment on lines +12 to +14
REPO_ROOT = Path(__file__).resolve().parent.parent
SCRIPT_PATH = REPO_ROOT / "polylogue.py"

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.

SCRIPT_PATH points to <repo>/polylogue.py, but this repository (and the packaged flake/app) appears to expose polylogue as a console script and does not include a top-level polylogue.py. The generated systemd/cron snippets will therefore be broken; prefer invoking the installed entry point (e.g., ${cfg.package}/bin/polylogue in Nix, or polylogue / python -m polylogue.cli).

Copilot uses AI. Check for mistakes.
Comment thread polylogue/automation.py
Comment on lines +39 to +42
def build_command(target: AutomationTarget, extra_args: Iterable[str]) -> str:
parts = [sys.executable, str(SCRIPT_PATH)] + target.command + list(extra_args)
return " ".join(parts)

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.

build_command() builds a single string via ' '.join(parts) without quoting/escaping. Paths like SCRIPT_PATH, working_dir, or --out values containing spaces will produce invalid systemd/cron snippets. Use proper escaping (e.g., systemd escaping rules for ExecStart= and shell quoting for cron) or generate an argv list and format per target scheduler.

Copilot uses AI. Check for mistakes.
Comment thread polylogue/cli.py
Comment on lines +1080 to +1087
target = TARGETS[args.target]
defaults = target.defaults or {}

if args.automation_format == "describe":
data = describe_targets(getattr(args, "target", None))
print(json.dumps(data, indent=2))
return

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.

run_automation_cli() indexes TARGETS[args.target] before handling the describe subcommand. Since automation describe allows --target to be omitted (to list all targets), this will raise when args.target is missing/None. Handle describe before looking up a specific target (or make --target required for describe if that’s the intent).

Suggested change
target = TARGETS[args.target]
defaults = target.defaults or {}
if args.automation_format == "describe":
data = describe_targets(getattr(args, "target", None))
print(json.dumps(data, indent=2))
return
if args.automation_format == "describe":
data = describe_targets(getattr(args, "target", None))
print(json.dumps(data, indent=2))
return
target = TARGETS[args.target]
defaults = target.defaults or {}

Copilot uses AI. Check for mistakes.
Comment thread polylogue/util.py
slug = f"{base}-{counter}"
counter += 1

provider_map[conversation_id] = {"slug": slug}

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.

assign_conversation_slug() overwrites any existing per-conversation state with {"slug": slug}. If an entry already exists (e.g., from a previous run or older state format) but lacks slug, this will discard fields like contentHash, dirty, attachmentsDir, etc. Update the existing dict in-place (set entry['slug']) instead of replacing the whole entry.

Suggested change
provider_map[conversation_id] = {"slug": slug}
if not isinstance(entry, dict):
entry = {}
entry["slug"] = slug
provider_map[conversation_id] = entry

Copilot uses AI. Check for mistakes.
Comment thread polylogue/util.py
entry = provider_map.get(conversation_id)
if not isinstance(entry, dict):
entry = {}
entry.update({k: v for k, v in updates.items() if v is not None})

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.

update_conversation_state() drops any updates where the value is None, which prevents callers from clearing previously-set fields (e.g., switching from html=True to html=False can’t clear htmlPath). Consider either (a) allowing None to explicitly clear keys, or (b) treating a separate sentinel/removal list as “delete this key” so state stays consistent across option changes.

Suggested change
entry.update({k: v for k, v in updates.items() if v is not None})
for k, v in updates.items():
if v is None:
entry.pop(k, None)
else:
entry[k] = v

Copilot uses AI. Check for mistakes.
Comment thread polylogue/drive_client.py
@@ -45,7 +46,25 @@ def ensure_credentials(self) -> Path:
"Missing credentials.json. Download a Google OAuth client secret and place it next to polylogue.py."

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.

In plain mode, the error message still instructs users to place credentials next to polylogue.py, but this PR introduces a packaged polylogue console script and the repo doesn’t appear to ship a top-level polylogue.py. Update the message to point at the actual credentials path ($XDG_CONFIG_HOME/polylogue/credentials.json) or the CLI packaging entry point.

Suggested change
"Missing credentials.json. Download a Google OAuth client secret and place it next to polylogue.py."
f"Missing credentials.json. Download a Google OAuth client secret and place it at {cred_path}."

Copilot uses AI. Check for mistakes.
Comment thread README.md
Comment on lines 45 to 52
Although the CLI is interactive by default, the same functionality is available non-interactively:
- `python3 polylogue.py render PATH [--out DIR] [--links-only] [--dry-run] [--force] [--collapse-threshold N] [--json] [--plain] [--diff]`
- `python3 polylogue.py sync [--folder-name NAME] [--folder-id ID] [--out DIR] [--links-only] [--since RFC3339] [--until RFC3339] [--name-filter REGEX] [--dry-run] [--force] [--prune] [--json] [--plain] [--diff]`
- `python3 polylogue.py sync-codex [--base-dir DIR] [--out DIR] [--collapse-threshold N] [--html] [--html-theme THEME] [--force] [--prune] [--all] [--json] [--diff]`
- `python3 polylogue.py sync-claude-code [--base-dir DIR] [--out DIR] [--collapse-threshold N] [--html] [--html-theme THEME] [--force] [--prune] [--all] [--json] [--diff]`
- `python3 polylogue.py list [--folder-name NAME] [--folder-id ID] [--since RFC3339] [--until RFC3339] [--name-filter REGEX] [--json] [--plain]`
- `python3 polylogue.py status`
- `python3 polylogue.py status [--json] [--watch] [--interval seconds]`
- `python3 polylogue.py import chatgpt EXPORT_PATH [--conversation-id ID ...] [--all] [--out DIR] [--collapse-threshold N] [--html] [--html-theme THEME] [--plain]`

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.

The README’s CLI examples still reference python3 polylogue.py ..., but the PR adds a polylogue console_script entry point and other code (e.g., automation) assumes packaging. If polylogue.py no longer exists, these examples will fail; update them to use polylogue ... (or python -m polylogue.cli ...) consistently.

Copilot uses AI. Check for mistakes.
Comment thread nix/modules/polylogue.nix
Comment on lines +90 to +106
meta = targetData.${name};
targetUser = targetCfg.user or cfg.user;
defaults = meta.defaults or {};
defaultExtra = lib.attrByPath ["extraArgs"] [] defaults;
defaultCollapse = lib.attrByPath ["collapseThreshold"] null defaults;
defaultHtml = lib.attrByPath ["html"] false defaults;
defaultOut = lib.attrByPath ["outputDir"] null defaults;
defaultWorking = lib.attrByPath ["workingDir"] null defaults;
workingDir = toString (targetCfg.workingDir or defaultWorking or cfg.workingDir);
baseArgs = meta.command
++ defaultExtra
++ targetCfg.extraArgs;
collapseValue = targetCfg.collapseThreshold or defaultCollapse;
argsWithCollapse = if collapseValue != null && !(lib.elem "--collapse-threshold" baseArgs)
then baseArgs ++ ["--collapse-threshold", toString collapseValue]
else baseArgs;
htmlFlag = if targetCfg.html then true else defaultHtml;

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.

Several ... or ... fallbacks here likely don’t work as intended because the options (e.g., user, workingDir, collapseThreshold) are always present in targetCfg but may be null. In that case targetCfg.user or cfg.user yields null (no fallback), and toString (targetCfg.workingDir or ...) can fail. Use explicit null-coalescing (e.g., if targetCfg.user != null then targetCfg.user else cfg.user, similarly for paths/thresholds) so defaults apply when the value is null.

Copilot uses AI. Check for mistakes.
Comment thread polylogue/automation.py
Comment on lines +7 to +22
from pathlib import Path
from textwrap import dedent
from typing import Dict, Iterable, List, Optional


REPO_ROOT = Path(__file__).resolve().parent.parent
SCRIPT_PATH = REPO_ROOT / "polylogue.py"


@dataclass
class AutomationTarget:
name: str
description: str
command: List[str]
defaults: Dict[str, Any] = field(default_factory=dict)

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.

This module uses typing names (Any, Tuple) in annotations but doesn’t import them (from typing import ...). Even with postponed evaluation, this breaks type-checking and will fail if anything calls typing.get_type_hints() on these symbols. Import the missing names or switch to built-in generics (dict[str, ...], tuple[...]) consistently.

Copilot uses AI. Check for mistakes.
Comment thread polylogue/automation.py
)
command = build_command(target, merged_args)
snippet = (
f"{schedule} XDG_STATE_HOME=\"{state_env}\" cd {working_dir} && {command} >> \"{log_path}\" 2>&1"

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.

The cron snippet sets XDG_STATE_HOME=... only for the cd command (XDG_STATE_HOME=... cd ... && ...), so the actual Polylogue invocation after && won’t see it. Move the env assignment to apply to the Polylogue command (or wrap the whole command in a shell).

Suggested change
f"{schedule} XDG_STATE_HOME=\"{state_env}\" cd {working_dir} && {command} >> \"{log_path}\" 2>&1"
f"{schedule} cd {working_dir} && XDG_STATE_HOME=\"{state_env}\" {command} >> \"{log_path}\" 2>&1"

Copilot uses AI. Check for mistakes.

@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: 23

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
polylogue/importers/chatgpt.py (1)

336-339: ⚠️ Potential issue | 🟡 Minor

Redundant conditional check on line 338.

Line 338 checks if content.get("content_type") == "text" and isinstance(parts, list), but parts is already confirmed to be a list on line 336. The condition on line 338 will never be reached because if parts is a list, line 337 returns.

🧹 Suggested fix
 def _extract_text(role: Optional[str], content: Dict) -> str:
     if not isinstance(content, dict):
         return ""
     parts = content.get("parts")
     if isinstance(parts, list):
         return _render_parts(parts)
-    if content.get("content_type") == "text" and isinstance(parts, list):
-        return _render_parts(parts)
     if isinstance(content.get("text"), str):
         return content["text"]
     return ""
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/importers/chatgpt.py` around lines 336 - 339, The second
conditional checking content.get("content_type") == "text" and isinstance(parts,
list) is redundant because the earlier if isinstance(parts, list): already
returns; remove the redundant conditional (or change the first to be more
specific if you intended to only render text parts) so that only one sensible
check remains—use the existing isinstance(parts, list) branch to call
_render_parts(parts) or, if behavior should be limited to text, make the first
check into if isinstance(parts, list) and content.get("content_type") == "text":
return _render_parts(parts).
polylogue/commands.py (1)

403-455: ⚠️ Potential issue | 🔴 Critical

Prune can delete slugged sync outputs.

persist_document() can now return a stable/deduplicated markdown_path that differs from sanitize_filename(meta["name"]). The downstream prune step still builds its keep-set from item.name, so duplicate titles or renamed chats can be classified as stale and removed immediately when --prune is enabled. Derive the keep-set from the final persisted path instead.

🛠️ Follow-up in the prune block
-        wanted = {sanitize_filename(item.name or item.id or "") for item in items}
+        wanted = {Path(item.output).stem for item in items}

Also applies to: 474-483

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

In `@polylogue/commands.py` around lines 403 - 455, The prune logic is building
its keep-set from the original item.name (sanitize_filename(meta["name"])) which
can differ from the stable/deduplicated path returned by persist_document;
update the code so the keep-set uses the final persisted path (use
persist_result.markdown_path or output_path when persist_result exists, falling
back to md_path) instead of item.name, and mirror the same change in the later
prune block that currently references item.name (the block handling prune at the
end of the flow) so duplicates/renamed chats are preserved correctly.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@nix/modules/polylogue.nix`:
- Around line 91-118: The fallback expressions like targetUser = targetCfg.user
or cfg.user and uses of or for workingDir, outputDir and collapseThreshold don't
handle attributes set to null; change them to explicit null checks so a present
null falls back correctly (e.g., set targetUser using if targetCfg.user != null
then targetCfg.user else cfg.user, compute workingDir from if
targetCfg.workingDir != null then targetCfg.workingDir else (if defaultWorking
!= null then defaultWorking else cfg.workingDir), and likewise for resolvedOut
and collapseValue), and replace cfg.user or "root" with an explicit if cfg.user
!= null then cfg.user else "root" so tmpfilesRules and args construction never
receive the literal null string.

In `@polylogue/automation.py`:
- Line 9: The file uses typing.Any and typing.Tuple on lines referenced (e.g.,
in type hints around functions/classes referenced at lines 21 and 108) but only
imports Dict, Iterable, List, Optional; add Any and Tuple to the import list at
the top (from typing import Dict, Iterable, List, Optional, Any, Tuple) or
alternatively replace usages with PEP 585 built-in generics and import Any if
needed (e.g., use dict[str, Any] or tuple[...]) so the names referenced in those
type hints are defined and F821 errors are resolved.
- Around line 12-13: The code currently hardcodes REPO_ROOT and SCRIPT_PATH
(REPO_ROOT / "polylogue.py") to build automation commands; replace that by
invoking the installed console entry point instead: remove/stop using
SCRIPT_PATH and change command construction to run the package module via the
Python interpreter (e.g., [sys.executable, "-m", "polylogue.cli", ...]) or
resolve the "polylogue" executable via shutil.which and use that, updating any
code that references SCRIPT_PATH or REPO_ROOT for command execution (e.g., where
automation commands are built) to use the entry-point invocation instead.

In `@polylogue/cli.py`:
- Around line 817-823: The current guard in run_watch_cli blocks all watch
commands when watch_directory is None, preventing the one-shot path from
reaching run_watch_codex/run_watch_claude_code; change the condition to allow
the command when args.once (or equivalent flag) is set. Specifically, update the
check that references watch_directory in run_watch_cli so it only prints the
error and returns when watch_directory is None AND args.once is False (i.e., if
not args.once); this lets the initial sync path proceed into run_watch_codex or
run_watch_claude_code for the --once case while preserving the existing
rejection for interactive watching.
- Around line 1077-1085: run_automation_cli currently indexes TARGETS using
TARGETS[args.target] before checking if args.automation_format == "describe",
causing a KeyError when args.target is None; fix by handling the describe case
first (check if args.automation_format == "describe" and call
describe_targets/getattr(args, "target", None) before any access to TARGETS) or
otherwise guard the TARGETS lookup (e.g., only compute target =
TARGETS[args.target] after confirming args.target is not None and
automation_format is not "describe") so describe can run without a target.

In `@polylogue/commands.py`:
- Around line 50-68: The provider aggregation misses mapping the explicit
commands "sync-codex" and "sync-claude-code", so runs appear as separate
providers; update PROVIDER_ALIASES (and/or _provider_from_cmd) to map
"sync-codex" -> "codex" and "sync-claude-code" -> "claude-code" (or add checks
in _provider_from_cmd to treat strings starting with
"sync-codex"/"sync-claude-code" as their respective providers) so those sync
runs fold into the Codex and Claude Code totals.

In `@polylogue/document_store.py`:
- Around line 214-218: The local-dirty protection incorrectly allows overwrites
when the on-disk file has been edited and either the remote conversation changed
or the state_entry lacks contentHash; update the logic around
read_existing_document, existing_dirty and state_entry so that missing
contentHash is treated as dirty and any existing_dirty true short-circuits the
update/merge path (avoid falling through to the overwrite at the later update
block). Concretely, set existing_dirty = True when stored_hash is falsy or when
existing.body_hash != stored_hash, and in the code paths that decide whether to
skip or to write (the branch that currently checks remote_same and later writes
at the overwrite location), add an explicit guard that returns/keeps the
existing.body when existing_dirty is true so the local file is not overwritten.
- Around line 197-203: The resolved slug (slug variable) must be sanitized
before being used to build filesystem paths: ensure that after choosing slug via
slug_hint, assign_conversation_slug, or the sanitize_filename fallback, you run
a final sanitizer (e.g., reuse sanitize_filename or a stricter sanitizer) to
strip path separators and traversal tokens; replace or fallback to a safe name
like "document" if the sanitized result is empty, and then use that sanitized
slug when constructing the markdown file path and attachments directory so
inputs such as "../notes/pwned" or "nested/name" cannot escape output_dir.
- Around line 394-404: The current code swallows all exceptions from
update_index (provider, conversation_id, slug, path) which hides backend errors;
change the bare except to catch Exception as e and log full details (use
logger.exception or similar) including provider, conversation_id, slug, and
markdown_path, then surface a degraded result instead of silently passing—either
propagate a wrapped IndexingError or return/mark the document's indexing status
as failed so callers can detect the degradation; ensure the change is made
around the update_index call in document_store.py.

In `@polylogue/importers/base.py`:
- Around line 15-20: The code accesses result.document.stats unguarded in
run_import_codex after calling import_codex_session and ImportResult may have
skipped=True and document=None; update the consumer (the loop handling
ImportResult instances in run_import_codex) to first check result.skipped is
False and result.document is not None before referencing result.document.stats
(or skip/continue when skipped or document is None), ensuring all uses of
result.document.stats are behind that guard.

In `@polylogue/importers/chatgpt.py`:
- Around line 184-185: Remove the two extra blank lines found in the chatgpt.py
module (around the region between existing functions/classes) so spacing matches
the project's style; collapse them to a single blank line so adjacent function
or class definitions (or imports) are separated consistently.

In `@polylogue/importers/claude_ai.py`:
- Around line 220-227: _index_export_files currently indexes files by path.name
only, breaking lookup in _copy_file which sometimes uses raw file_id without
extension; modify _index_export_files to also map path.stem -> path (in addition
to path.name) so attachments referenced by stem resolve; ensure you handle
potential collisions by keeping the first-seen mapping or overriding explicitly
and reference the functions _index_export_files and _copy_file when making the
change.

In `@polylogue/index_qdrant.py`:
- Around line 32-38: The current code calls client.recreate_collection on any
Exception from client.get_collection, which risks deleting data on transient
errors; change the try/except to only catch the specific REST error that
indicates “collection not found”
(qdrant_client.http.exceptions.UnexpectedResponse) and verify the HTTP status is
404 before calling client.recreate_collection (leave other exceptions
unhandled/raised). Locate the block using client.get_collection and
client.recreate_collection with rest.VectorParams(size=size,
distance=rest.Distance.COSINE) and replace the broad except Exception with a
conditional catch that checks for UnexpectedResponse and response.status_code ==
404, re-raising other errors.

In `@polylogue/index_sqlite.py`:
- Around line 53-101: Replace the manual connect/try/finally with a connection
context manager: open the DB using "with sqlite3.connect(db_path) as conn:" then
call _ensure_schema(conn), perform the conn.execute(...) calls and call
conn.commit() at the end; remove the explicit conn.close() in the finally block
(the context manager will close and automatically rollback on exceptions). Keep
the same SQL statements and use of conn.execute, _ensure_schema, and conn.commit
to preserve behavior.

In `@polylogue/index.py`:
- Around line 34-38: The current branch in polylogue/index.py silently returns
when ImportError occurs for "from .index_qdrant import update_qdrant_index",
which hides misconfiguration when POLYLOGUE_INDEX_BACKEND is set to "qdrant";
modify the except ImportError block to log a clear warning (use the module
logger or Python logging) that POLYLOGUE_INDEX_BACKEND==qdrant but the qdrant
dependency is missing and indexing will be skipped, include the ImportError
message in the log to aid debugging and then return as before.
- Line 5: Replace the deprecated typing.Dict with the built-in dict type in the
import and all type annotations: remove Dict from the "from typing import Any,
Dict" import in polylogue/index.py (keep Any if still used) and update any
annotations that use Dict[...] to use dict[..., ...] instead (search for
occurrences of Dict in function signatures, variable annotations, and return
types to update them).

In `@polylogue/local_sync.py`:
- Around line 84-91: The skip branch currently swallows exceptions with a bare
try/except around snapshot.unlink(); replace that with
contextlib.suppress(Exception) to cleanly ignore unlink errors—locate the block
testing result.skipped where snapshot may be non-None, wrap snapshot.unlink() in
a contextlib.suppress(Exception) and keep the existing skipped += 1 and continue
behavior intact.

In `@polylogue/util.py`:
- Around line 120-159: assign_conversation_slug uses _load_state() and
_save_state() non-atomically which can cause duplicate slugs under concurrent
runs; protect state file access by acquiring an exclusive file lock around the
read-modify-write sequence (wrap the logic inside assign_conversation_slug or
create a helper like _with_state_lock) using fcntl.flock on a lock file (e.g.,
same path as the state file with a .lock suffix), ensure the state directory
exists before opening the lock, then call _load_state(), mutate provider_map and
set provider_map[conversation_id], call _save_state(), and finally release the
lock so concurrent processes serialize slug assignment.

In `@pyproject.toml`:
- Around line 12-27: The pyproject.toml currently lists unpinned runtime
packages in the dependencies array which risks nondeterministic builds; update
the dependencies list in pyproject.toml to pin versions (at least major or
minor, e.g., "google-api-python-client==X.Y.Z") or add a generated lockfile and
reference it (e.g., requirements.lock or poetry.lock) to ensure reproducible
installs; modify the dependencies array entries to include explicit version
specifiers for the entries shown (google-api-python-client,
google-auth-oauthlib, google-auth-httplib2, pathvalidate, aiohttp, aiofiles,
google-generativeai, rich, pydantic, python-frontmatter, jinja2, markdown-it-py,
pyperclip, watchfiles) or commit a lockfile generated by pip-tools/poetry and
update CI/install docs accordingly.

In `@README.md`:
- Line 98: The README is missing documentation for the
POLYLOGUE_QDRANT_VECTOR_SIZE environment variable referenced in
polylogue/index_qdrant.py; update the sentence that lists Qdrant knobs to also
mention POLYLOGUE_QDRANT_VECTOR_SIZE, briefly describe that it controls the
embedding/vector dimensionality used when creating or validating Qdrant
collections (and note the default if applicable), and mention that mismatches
between this value and existing collection vector_size can cause errors so users
should set it to match their embeddings.
- Around line 74-92: Fix the Markdown spacing around the "## Nix Flake Usage"
heading and the fenced code block to satisfy MD022/MD031: ensure there is
exactly one blank line before and after the "## Nix Flake Usage" heading and add
a blank line immediately before the opening ```nix and after the closing ```
code fence in that section so the heading and code block are separated properly
from surrounding text and the subsequent "## Configuration" heading.

In `@tests/test_automation_snippets.py`:
- Around line 56-63: The compound assertion in test_describe_targets_roundtrip()
mixes multiple membership checks which obscures which target is missing; replace
the single assert ("codex" in data and "claude-code" in data and "drive-sync" in
data and "gemini-render" in data) with separate assertions for each target
(e.g., assert "codex" in data; assert "claude-code" in data; assert "drive-sync"
in data; assert "gemini-render" in data) so failures clearly indicate which
describe_targets() entry is absent, keeping the rest of the test (calls to
describe_targets("codex") and describe_targets("drive-sync") and subsequent
checks) unchanged.

---

Outside diff comments:
In `@polylogue/commands.py`:
- Around line 403-455: The prune logic is building its keep-set from the
original item.name (sanitize_filename(meta["name"])) which can differ from the
stable/deduplicated path returned by persist_document; update the code so the
keep-set uses the final persisted path (use persist_result.markdown_path or
output_path when persist_result exists, falling back to md_path) instead of
item.name, and mirror the same change in the later prune block that currently
references item.name (the block handling prune at the end of the flow) so
duplicates/renamed chats are preserved correctly.

In `@polylogue/importers/chatgpt.py`:
- Around line 336-339: The second conditional checking
content.get("content_type") == "text" and isinstance(parts, list) is redundant
because the earlier if isinstance(parts, list): already returns; remove the
redundant conditional (or change the first to be more specific if you intended
to only render text parts) so that only one sensible check remains—use the
existing isinstance(parts, list) branch to call _render_parts(parts) or, if
behavior should be limited to text, make the first check into if
isinstance(parts, list) and content.get("content_type") == "text": return
_render_parts(parts).
🪄 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: f2c3d2ec-04fe-4163-b939-f7bc4a059265

📥 Commits

Reviewing files that changed from the base of the PR and between 991715a and d2ff434.

📒 Files selected for processing (26)
  • README.md
  • flake.nix
  • nix/devshell.nix
  • nix/modules/polylogue.nix
  • polylogue/automation.py
  • polylogue/automation_targets.json
  • polylogue/cli.py
  • polylogue/commands.py
  • polylogue/document_store.py
  • polylogue/drive_client.py
  • polylogue/importers/base.py
  • polylogue/importers/chatgpt.py
  • polylogue/importers/claude_ai.py
  • polylogue/importers/claude_code.py
  • polylogue/importers/codex.py
  • polylogue/index.py
  • polylogue/index_qdrant.py
  • polylogue/index_sqlite.py
  • polylogue/local_sync.py
  • polylogue/options.py
  • polylogue/util.py
  • pyproject.toml
  • tests/test_automation_snippets.py
  • tests/test_commands_logic.py
  • tests/test_importers_multi.py
  • tests/test_status.py

Comment thread nix/modules/polylogue.nix
Comment on lines +91 to +118
targetUser = targetCfg.user or cfg.user;
defaults = meta.defaults or {};
defaultExtra = lib.attrByPath ["extraArgs"] [] defaults;
defaultCollapse = lib.attrByPath ["collapseThreshold"] null defaults;
defaultHtml = lib.attrByPath ["html"] false defaults;
defaultOut = lib.attrByPath ["outputDir"] null defaults;
defaultWorking = lib.attrByPath ["workingDir"] null defaults;
workingDir = toString (targetCfg.workingDir or defaultWorking or cfg.workingDir);
baseArgs = meta.command
++ defaultExtra
++ targetCfg.extraArgs;
collapseValue = targetCfg.collapseThreshold or defaultCollapse;
argsWithCollapse = if collapseValue != null && !(lib.elem "--collapse-threshold" baseArgs)
then baseArgs ++ ["--collapse-threshold", toString collapseValue]
else baseArgs;
htmlFlag = if targetCfg.html then true else defaultHtml;
argsWithHtml = if htmlFlag && !(lib.elem "--html" argsWithCollapse)
then argsWithCollapse ++ ["--html"]
else if (!htmlFlag)
then lib.filter (arg: arg != "--html") argsWithCollapse
else argsWithCollapse;
resolvedOut = targetCfg.outputDir or defaultOut;
args = if resolvedOut != null && !(lib.elem "--out" argsWithHtml)
then argsWithHtml ++ ["--out", toString resolvedOut]
else argsWithHtml;
envVars = cfg.environment // targetCfg.environment // {
XDG_STATE_HOME = toString cfg.stateDir;
};

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 | 🔴 Critical

🧩 Analysis chain

🌐 Web query:

In Nix, does cfg.user or "root"fall back whencfg.userexists but isnull, or only when the attribute is missing? For nullOroptions, isif x != null then x else y the correct fallback pattern?

💡 Result:

cfg.user or "root" only falls back when the attribute is missing, not when it exists with the value null.

  • In Nix, or in this position is part of attribute selection with a default: if the selected attribute “doesn’t exist, return the expr after or”. (manual.determinate.systems)
  • Therefore, if cfg.user exists and is null, the expression evaluates to null (no fallback). (reddit.com)

For nullOr options, the usual fallback pattern is exactly:

if x != null then x else y

(Equivalently: if x == null then y else x.)

Citations:


🏁 Script executed:

# Check if the file exists and get relevant sections
wc -l nix/modules/polylogue.nix
echo "---"
sed -n '85,125p' nix/modules/polylogue.nix
echo "---"
sed -n '155,170p' nix/modules/polylogue.nix

Repository: Sinity/polylogue

Length of output: 2511


🏁 Script executed:

# Look at the module options definition to see what types cfg.user, targetCfg.user, etc. are
sed -n '165,226p' nix/modules/polylogue.nix | head -50
echo "---"
# Also search for option definitions to understand types
rg "user.*=" nix/modules/polylogue.nix -A 2

Repository: Sinity/polylogue

Length of output: 1691


🏁 Script executed:

# Check the per-target submodule option types
sed -n '1,165p' nix/modules/polylogue.nix | tail -50
echo "---"
# Also search for targetOption or submodule definition
rg "workingDir|outputDir|collapseThreshold" nix/modules/polylogue.nix -B 2 -A 2

Repository: Sinity/polylogue

Length of output: 4419


🏁 Script executed:

# Verify line 127 and surrounding context to see how targetUser is used
sed -n '120,135p' nix/modules/polylogue.nix
echo "---"
# Verify the full context for tmpfilesRules
sed -n '155,165p' nix/modules/polylogue.nix

Repository: Sinity/polylogue

Length of output: 913


These or fallbacks do not handle null option values in Nix.

In Nix, targetCfg.user or cfg.user and cfg.user or "root" only fall back when the attribute is missing, not when it exists with null. Since these options define nullOr types with default = null, the fallback pattern fails and leaves owner = null in tmpfilesRules (line 160), which generates malformed tmpfiles.d entries with the literal string "null". The same issue affects workingDir, outputDir, and collapseThreshold, though they are conditionally used via != null checks.

Use explicit null checks instead:

Fixes
-      targetUser = targetCfg.user or cfg.user;
+      targetUser = if targetCfg.user != null then targetCfg.user else cfg.user;

-      workingDir = toString (targetCfg.workingDir or defaultWorking or cfg.workingDir);
+      workingDir = toString (
+        if targetCfg.workingDir != null then targetCfg.workingDir
+        else if defaultWorking != null then defaultWorking
+        else cfg.workingDir
+      );

-      collapseValue = targetCfg.collapseThreshold or defaultCollapse;
+      collapseValue =
+        if targetCfg.collapseThreshold != null then targetCfg.collapseThreshold else defaultCollapse;

-      resolvedOut = targetCfg.outputDir or defaultOut;
+      resolvedOut = if targetCfg.outputDir != null then targetCfg.outputDir else defaultOut;

-    let owner = cfg.user or "root"; in
+    let owner = if cfg.user != null then cfg.user else "root"; in
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@nix/modules/polylogue.nix` around lines 91 - 118, The fallback expressions
like targetUser = targetCfg.user or cfg.user and uses of or for workingDir,
outputDir and collapseThreshold don't handle attributes set to null; change them
to explicit null checks so a present null falls back correctly (e.g., set
targetUser using if targetCfg.user != null then targetCfg.user else cfg.user,
compute workingDir from if targetCfg.workingDir != null then
targetCfg.workingDir else (if defaultWorking != null then defaultWorking else
cfg.workingDir), and likewise for resolvedOut and collapseValue), and replace
cfg.user or "root" with an explicit if cfg.user != null then cfg.user else
"root" so tmpfilesRules and args construction never receive the literal null
string.

Comment thread polylogue/automation.py
from importlib import resources
from pathlib import Path
from textwrap import dedent
from typing import Dict, Iterable, List, Optional

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== typing imports =="
sed -n '1,12p' polylogue/automation.py

echo
echo "== unresolved typing names used later in the file =="
rg -n '\bAny\b|\bTuple\b' polylogue/automation.py

Repository: Sinity/polylogue

Length of output: 529


Import Any and Tuple from typing, or use built-in generics.

Lines 21 and 108 use Any and Tuple that are not imported on line 9. This causes F821 undefined name errors. Given the from __future__ import annotations at the top of the file, you can instead use lowercase generics: dict[str, Any] and tuple[...] (though Any would still need to be imported if evaluated at runtime).

Also applies to: 21-21, 108-108

🧰 Tools
🪛 Ruff (0.15.9)

[warning] 9-9: Import from collections.abc instead: Iterable

Import from collections.abc

(UP035)


[warning] 9-9: typing.Dict is deprecated, use dict instead

(UP035)


[warning] 9-9: typing.List is deprecated, use list instead

(UP035)

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

In `@polylogue/automation.py` at line 9, The file uses typing.Any and typing.Tuple
on lines referenced (e.g., in type hints around functions/classes referenced at
lines 21 and 108) but only imports Dict, Iterable, List, Optional; add Any and
Tuple to the import list at the top (from typing import Dict, Iterable, List,
Optional, Any, Tuple) or alternatively replace usages with PEP 585 built-in
generics and import Any if needed (e.g., use dict[str, Any] or tuple[...]) so
the names referenced in those type hints are defined and F821 errors are
resolved.

Comment thread polylogue/automation.py
Comment on lines +12 to +13
REPO_ROOT = Path(__file__).resolve().parent.parent
SCRIPT_PATH = REPO_ROOT / "polylogue.py"

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== automation command construction =="
sed -n '12,41p' polylogue/automation.py

echo
echo "== declared console entry points =="
pyproject="$(fd '^pyproject\.toml$' | head -n1 || true)"
if [ -n "${pyproject:-}" ]; then
  sed -n '/^\[project\.scripts\]/,/^\[/p' "$pyproject"
fi

echo
echo "== repo-level launcher files =="
fd '^polylogue\.py$'

Repository: Sinity/polylogue

Length of output: 1178


Resolve generated automation commands through the installed CLI entry point, not a non-existent repo-relative script.

Lines 12–13 and 39–41 hardcode a path to REPO_ROOT / "polylogue.py", which does not exist even in the source tree. This will cause all generated automation commands to fail at runtime. The project already declares a console entry point (polylogue = "polylogue.cli:main" in pyproject.toml), which should be used instead of a fragile checkout-relative path.

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

In `@polylogue/automation.py` around lines 12 - 13, The code currently hardcodes
REPO_ROOT and SCRIPT_PATH (REPO_ROOT / "polylogue.py") to build automation
commands; replace that by invoking the installed console entry point instead:
remove/stop using SCRIPT_PATH and change command construction to run the package
module via the Python interpreter (e.g., [sys.executable, "-m", "polylogue.cli",
...]) or resolve the "polylogue" executable via shutil.which and use that,
updating any code that references SCRIPT_PATH or REPO_ROOT for command execution
(e.g., where automation commands are built) to use the entry-point invocation
instead.

Comment thread polylogue/automation.py
Comment on lines +39 to +41
def build_command(target: AutomationTarget, extra_args: Iterable[str]) -> str:
parts = [sys.executable, str(SCRIPT_PATH)] + target.command + list(extra_args)
return " ".join(parts)

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== source =="
sed -n '39,41p;180,182p' polylogue/automation.py

tmpdir="$(mktemp -d)"
mkdir -p "$tmpdir/dir with spaces"

echo
echo "== env assignment before cd does not reach the next command =="
if ( XDG_STATE_HOME="$tmpdir/state" cd "$tmpdir/dir with spaces" && env | grep -q '^XDG_STATE_HOME=' ); then
  echo "unexpected: XDG_STATE_HOME persisted"
else
  echo "expected: XDG_STATE_HOME is not exported to the command after &&"
fi

echo
echo "== unquoted working_dir is split by the shell =="
if sh -c "cd $tmpdir/dir with spaces" 2>/dev/null; then
  echo "unexpected: unquoted path succeeded"
else
  echo "expected: unquoted working_dir fails"
fi

Repository: Sinity/polylogue

Length of output: 605


🏁 Script executed:

# View the full context around lines 39-41 and 180-182
head -200 polylogue/automation.py | tail -100 | cat -n

Repository: Sinity/polylogue

Length of output: 3139


🏁 Script executed:

# Get full context for lines 39-41 with surrounding code
sed -n '30,50p' polylogue/automation.py | cat -n

# Get full context for lines 180-182 with surrounding code  
sed -n '170,195p' polylogue/automation.py | cat -n

Repository: Sinity/polylogue

Length of output: 1483


🏁 Script executed:

# Find SCRIPT_PATH definition
rg 'SCRIPT_PATH\s*=' polylogue/automation.py | head -5

# Find all usages of build_command
rg 'build_command' polylogue/automation.py

# Check if there are other files that might use these functions
fd -e py | xargs rg 'from.*automation import|import.*automation' | head -10

Repository: Sinity/polylogue

Length of output: 593


🏁 Script executed:

# Check test file to understand expected behavior
cat -n tests/test_automation_snippets.py | head -80

Repository: Sinity/polylogue

Length of output: 3063


🏁 Script executed:

# Check if there are any tests that use paths with spaces
rg 'space' tests/test_automation_snippets.py

# Look for any test that might cover the space scenario
rg '\bcd\b' tests/test_automation_snippets.py -B 2 -A 2

# Check if cron output is actually tested to be valid shell
sed -n '39,54p' tests/test_automation_snippets.py | cat -n

Repository: Sinity/polylogue

Length of output: 932


Fix shell injection vulnerabilities in cron snippet generation.

The build_command() function flattens argv with space-joining, which breaks when sys.executable, SCRIPT_PATH, extra_args, or working_dir contain spaces or shell metacharacters. The cron_snippet() function embeds the result unquoted into a shell command string, making it vulnerable to injection and field splitting.

Additionally, XDG_STATE_HOME assignment doesn't reach the command after cd due to shell scoping: the env var is only available to the cd builtin, not to subsequent pipeline commands.

Keep argv as a list within build_command(), shell-quote it when rendering the cron entry, and assign environment variables directly to the command invocation instead of via cd chaining.

This also applies to the cron_snippet() generation at lines 96-98.

🧰 Tools
🪛 Ruff (0.15.9)

[warning] 40-40: Consider iterable unpacking instead of concatenation

Replace with iterable unpacking

(RUF005)

Comment thread polylogue/cli.py
Comment on lines +817 to +823
def run_watch_cli(args: argparse.Namespace, env: CommandEnv) -> None:
if watch_directory is None:
env.ui.console.print(
"[red]The watchfiles package is not available. Enable it in your environment to use watcher commands."
)
return
if args.watch_target == "codex":

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

Allow watch ... --once without watchfiles.

The one-shot path never enters the watch loop, but this guard rejects the command before run_watch_codex() / run_watch_claude_code() can do the initial sync. That breaks the documented --once mode in environments where the optional dependency is absent.

🛠️ Minimal fix
 def run_watch_cli(args: argparse.Namespace, env: CommandEnv) -> None:
-    if watch_directory is None:
+    if watch_directory is None and not getattr(args, "once", False):
         env.ui.console.print(
             "[red]The watchfiles package is not available. Enable it in your environment to use watcher commands."
         )
         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 run_watch_cli(args: argparse.Namespace, env: CommandEnv) -> None:
if watch_directory is None:
env.ui.console.print(
"[red]The watchfiles package is not available. Enable it in your environment to use watcher commands."
)
return
if args.watch_target == "codex":
def run_watch_cli(args: argparse.Namespace, env: CommandEnv) -> None:
if watch_directory is None and not getattr(args, "once", False):
env.ui.console.print(
"[red]The watchfiles package is not available. Enable it in your environment to use watcher commands."
)
return
if args.watch_target == "codex":
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/cli.py` around lines 817 - 823, The current guard in run_watch_cli
blocks all watch commands when watch_directory is None, preventing the one-shot
path from reaching run_watch_codex/run_watch_claude_code; change the condition
to allow the command when args.once (or equivalent flag) is set. Specifically,
update the check that references watch_directory in run_watch_cli so it only
prints the error and returns when watch_directory is None AND args.once is False
(i.e., if not args.once); this lets the initial sync path proceed into
run_watch_codex or run_watch_claude_code for the --once case while preserving
the existing rejection for interactive watching.

Comment thread polylogue/util.py
Comment on lines +120 to +159
def assign_conversation_slug(
provider: str,
conversation_id: str,
title: Optional[str],
*,
id_hint: Optional[str] = None,
) -> str:
st = _load_state()
convs = st.setdefault("conversations", {})
if not isinstance(convs, dict):
convs = {}
st["conversations"] = convs
provider_map = convs.setdefault(provider, {})
if not isinstance(provider_map, dict):
provider_map = {}
convs[provider] = provider_map

entry = provider_map.get(conversation_id)
if isinstance(entry, dict) and entry.get("slug"):
return entry["slug"]

base_source = title or id_hint or conversation_id or "conversation"
base = sanitize_filename(base_source)
if not base:
base = conversation_id[:8] if conversation_id else "conversation"

existing_slugs = {
data.get("slug")
for data in provider_map.values()
if isinstance(data, dict) and data.get("slug")
}
slug = base
counter = 1
while slug in existing_slugs:
slug = f"{base}-{counter}"
counter += 1

provider_map[conversation_id] = {"slug": slug}
_save_state(st)
return slug

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

Potential race condition in slug assignment.

_load_state() and _save_state() are not atomic. If two processes call assign_conversation_slug() concurrently for different conversations, they could both generate the same slug before either persists. For a single-user CLI this is low risk, but worth noting.

Consider using file locking (fcntl.flock on Unix) if concurrent automation runs are expected:

🛡️ Suggested defensive pattern (optional)
import fcntl

def _with_state_lock(fn):
    """Decorator to serialize state file access."""
    def wrapper(*args, **kwargs):
        STATE_PATH.parent.mkdir(parents=True, exist_ok=True)
        lock_path = STATE_PATH.with_suffix(".lock")
        with lock_path.open("w") as lock_file:
            fcntl.flock(lock_file, fcntl.LOCK_EX)
            try:
                return fn(*args, **kwargs)
            finally:
                fcntl.flock(lock_file, fcntl.LOCK_UN)
    return wrapper
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/util.py` around lines 120 - 159, assign_conversation_slug uses
_load_state() and _save_state() non-atomically which can cause duplicate slugs
under concurrent runs; protect state file access by acquiring an exclusive file
lock around the read-modify-write sequence (wrap the logic inside
assign_conversation_slug or create a helper like _with_state_lock) using
fcntl.flock on a lock file (e.g., same path as the state file with a .lock
suffix), ensure the state directory exists before opening the lock, then call
_load_state(), mutate provider_map and set provider_map[conversation_id], call
_save_state(), and finally release the lock so concurrent processes serialize
slug assignment.

Comment thread pyproject.toml
Comment on lines +12 to +27
dependencies = [
"google-api-python-client",
"google-auth-oauthlib",
"google-auth-httplib2",
"pathvalidate",
"aiohttp",
"aiofiles",
"google-generativeai",
"rich",
"pydantic",
"python-frontmatter",
"jinja2",
"markdown-it-py",
"pyperclip",
"watchfiles",
]

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 pinning dependency versions for reproducibility.

All runtime dependencies are unpinned, which can lead to inconsistent builds when upstream packages release breaking changes. For an application (vs. a library), pinning major versions or using a lockfile is recommended for deployment stability.

Example for critical dependencies:

 dependencies = [
-  "google-api-python-client",
+  "google-api-python-client>=2.0,<3.0",
   ...
-  "pydantic",
+  "pydantic>=2.0,<3.0",

Alternatively, consider generating a requirements.lock or using pip-tools for reproducible installs.

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

In `@pyproject.toml` around lines 12 - 27, The pyproject.toml currently lists
unpinned runtime packages in the dependencies array which risks nondeterministic
builds; update the dependencies list in pyproject.toml to pin versions (at least
major or minor, e.g., "google-api-python-client==X.Y.Z") or add a generated
lockfile and reference it (e.g., requirements.lock or poetry.lock) to ensure
reproducible installs; modify the dependencies array entries to include explicit
version specifiers for the entries shown (google-api-python-client,
google-auth-oauthlib, google-auth-httplib2, pathvalidate, aiohttp, aiofiles,
google-generativeai, rich, pydantic, python-frontmatter, jinja2, markdown-it-py,
pyperclip, watchfiles) or commit a lockfile generated by pip-tools/poetry and
update CI/install docs accordingly.

Comment thread README.md
Comment on lines +74 to 92
## Nix Flake Usage
- This repository is a self-contained flake: add `inputs.polylogue.url = "github:yourname/polylogue";` (or your fork) to another flake and reference the packaged CLI as `inputs.polylogue.packages.${system}.polylogue` or `inputs.polylogue.apps.${system}.polylogue`.
- Import the NixOS module via `imports = [ inputs.polylogue.nixosModules.polylogue ];` to enable declarative automation. Example:
```nix
services.polylogue = {
enable = true;
user = "polylogue";
workingDir = "/var/lib/polylogue";
targets.codex = {
enable = true;
outputDir = "/realm/data/chatlog/markdown/codex";
timer.interval = "10m";
};
targets."claude-code".enable = true;
};
```
- The module reads the same automation metadata as the CLI (see `polylogue automation describe --target codex`) and wires systemd timers around the packaged binary. Override `targets.<name>.extraArgs`, `collapseThreshold`, `html`, or set per-target `workingDir`/`outputDir` as needed.

## Configuration

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

Fix the blank-line spacing in this Markdown section.

The heading/code-fence spacing around ## Nix Flake Usage is tripping markdownlint (MD022/MD031), so this docs change will keep the docs lint job red.

🧰 Tools
🪛 markdownlint-cli2 (0.22.0)

[warning] 74-74: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below

(MD022, blanks-around-headings)


[warning] 77-77: Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)


[warning] 89-89: Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)


[warning] 92-92: 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 74 - 92, Fix the Markdown spacing around the "## Nix
Flake Usage" heading and the fenced code block to satisfy MD022/MD031: ensure
there is exactly one blank line before and after the "## Nix Flake Usage"
heading and add a blank line immediately before the opening ```nix and after the
closing ``` code fence in that section so the heading and code block are
separated properly from surrounding text and the subsequent "## Configuration"
heading.

Comment thread README.md
- Run state (`state.json`, `runs.json`) lives under `$XDG_STATE_HOME/polylogue/` so automation can tail recent activity.
- `polylogue doctor` reports the discovered paths when no config is detected.
- Drive behaviour can be tuned with environment variables such as `$POLYLOGUE_RETRIES`, `$POLYLOGUE_RETRY_BASE`, `$POLYLOGUE_AUTH_MODE`, and `$POLYLOGUE_TOKEN_PATH`.
- Indexing backends are controlled via `$POLYLOGUE_INDEX_BACKEND` (`sqlite`, `qdrant`, or `none`) alongside optional Qdrant knobs (`POLYLOGUE_QDRANT_URL`, `POLYLOGUE_QDRANT_API_KEY`, `POLYLOGUE_QDRANT_COLLECTION`).

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

Document POLYLOGUE_QDRANT_VECTOR_SIZE too.

polylogue/index_qdrant.py also reads POLYLOGUE_QDRANT_VECTOR_SIZE. Without it here, users cannot discover how to configure a non-default vector size or diagnose collection-size mismatches.

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

In `@README.md` at line 98, The README is missing documentation for the
POLYLOGUE_QDRANT_VECTOR_SIZE environment variable referenced in
polylogue/index_qdrant.py; update the sentence that lists Qdrant knobs to also
mention POLYLOGUE_QDRANT_VECTOR_SIZE, briefly describe that it controls the
embedding/vector dimensionality used when creating or validating Qdrant
collections (and note the default if applicable), and mention that mismatches
between this value and existing collection vector_size can cause errors so users
should set it to match their embeddings.

Comment on lines +56 to +63
def test_describe_targets_roundtrip():
data = describe_targets()
assert "codex" in data and "claude-code" in data and "drive-sync" in data and "gemini-render" in data
codex = describe_targets("codex")
assert list(codex.keys()) == ["codex"]
assert codex["codex"]["command"][0] == "sync-codex"
drive = describe_targets("drive-sync")
assert drive["drive-sync"]["command"][0] == "sync"

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 splitting compound assertions for clearer failure messages.

The assertion on line 58 combines multiple checks. If one fails, it's harder to identify which target is missing.

💡 Minor improvement
 def test_describe_targets_roundtrip():
     data = describe_targets()
-    assert "codex" in data and "claude-code" in data and "drive-sync" in data and "gemini-render" in data
+    assert "codex" in data
+    assert "claude-code" in data
+    assert "drive-sync" in data
+    assert "gemini-render" in data
     codex = describe_targets("codex")
📝 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 test_describe_targets_roundtrip():
data = describe_targets()
assert "codex" in data and "claude-code" in data and "drive-sync" in data and "gemini-render" in data
codex = describe_targets("codex")
assert list(codex.keys()) == ["codex"]
assert codex["codex"]["command"][0] == "sync-codex"
drive = describe_targets("drive-sync")
assert drive["drive-sync"]["command"][0] == "sync"
def test_describe_targets_roundtrip():
data = describe_targets()
assert "codex" in data
assert "claude-code" in data
assert "drive-sync" in data
assert "gemini-render" in data
codex = describe_targets("codex")
assert list(codex.keys()) == ["codex"]
assert codex["codex"]["command"][0] == "sync-codex"
drive = describe_targets("drive-sync")
assert drive["drive-sync"]["command"][0] == "sync"
🧰 Tools
🪛 Ruff (0.15.9)

[warning] 58-58: 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_automation_snippets.py` around lines 56 - 63, The compound
assertion in test_describe_targets_roundtrip() mixes multiple membership checks
which obscures which target is missing; replace the single assert ("codex" in
data and "claude-code" in data and "drive-sync" in data and "gemini-render" in
data) with separate assertions for each target (e.g., assert "codex" in data;
assert "claude-code" in data; assert "drive-sync" in data; assert
"gemini-render" in data) so failures clearly indicate which describe_targets()
entry is absent, keeping the rest of the test (calls to
describe_targets("codex") and describe_targets("drive-sync") and subsequent
checks) unchanged.

@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/feat/automation-persistence-nixos branch April 9, 2026 23:02
Sinity added a commit that referenced this pull request Apr 22, 2026
… module (#10)

Introduce infrastructure for unattended operation: a persistence layer
that deduplicates writes across reruns, file watchers for continuous
sync, systemd/cron snippet generation, and a NixOS module that wires
it all into declarative timers.

Document persistence (polylogue/document_store.py):
- persist_document() centralizes Markdown/HTML write logic previously
  duplicated across every importer and both render/sync commands
- Content-hash comparison skips unchanged conversations on rerun
- Dirty-local detection: when the on-disk body diverges from the stored
  hash, the importer preserves local edits and marks the entry dirty
  rather than overwriting
- Front matter gains a `polylogue:` metadata block tracking slug,
  provider, contentHash, collapseThreshold, attachmentPolicy, and
  dirty state
- All four importers (chatgpt, claude_ai, claude_code, codex) and
  both render_command/sync_command now route through persist_document()

Automation targets (polylogue/automation.py, automation_targets.json):
- JSON registry defines five targets (codex, claude-code, drive-sync,
  gemini-render, chatgpt-import) with per-target default args
- systemd_snippet() and cron_snippet() generate ready-to-use scheduler
  entries with merged defaults and user overrides
- CLI gains `polylogue automation systemd|cron|describe` subcommands

File watchers (polylogue/cli.py):
- `polylogue watch codex` and `polylogue watch claude-code` use
  watchfiles to trigger sync on JSONL changes with configurable
  debounce; `--once` runs a single pass and exits
- Watch runs log to the same telemetry as scheduled runs

Indexing backends (polylogue/index.py, index_sqlite.py, index_qdrant.py):
- Every persist_document() call updates a SQLite FTS5 index by default
- POLYLOGUE_INDEX_BACKEND env var selects sqlite, qdrant, or none
- SQLite schema: conversations table with content_hash, tokens, dirty
  columns plus an FTS5 virtual table for full-text search

NixOS module (nix/modules/polylogue.nix):
- Declarative services.polylogue option tree with per-target enable,
  outputDir, timer interval/bootDelay, collapseThreshold, html, and
  environment overrides
- Reads automation_targets.json at eval time to validate target names
  and wire default commands into systemd service ExecStart lines
- tmpfiles rules ensure working/output/state directories exist

Nix packaging (flake.nix, pyproject.toml):
- pyproject.toml defines build metadata, dependencies, and the
  polylogue console_scripts entry point
- flake.nix replaces inline check with buildPythonApplication, exports
  packages, apps, devShells.ci, and nixosModules outputs
- devshell gains pyperclip and watchfiles

State and CLI enhancements:
- util.py: assign_conversation_slug() allocates stable provider-scoped
  slugs; conversation_is_current() drives skip logic;
  read_clipboard_text()/write_clipboard_text() wrap pyperclip
- status command gains --json, --watch, --interval flags and a
  provider-level summary that aggregates across command types
- ImportResult grows skipped/skip_reason/dirty/content_hash fields;
  summarize_import() accounts for skipped conversations
- --to-clipboard flag on render and all import subcommands

Documentation:
- multi-provider.md deleted; content split into five per-provider
  docs under docs/providers/ (chatgpt, claude-ai, claude-code,
  gemini, openai-codex)
- README updated with watcher usage, automation targets, NixOS
  module example, and indexing backend configuration
@Sinity

Sinity commented Apr 28, 2026

Copy link
Copy Markdown
Owner Author

🤖 Post-hoc audit note: this PR received bot review feedback verified against current HEAD as part of #544. 4 finding(s) confirmed still present → tracked in #550. 9 finding(s) confirmed fixed/stale.

Sinity added a commit that referenced this pull request May 29, 2026
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]>
@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:pipeline Pipeline area:storage Storage faux-pull-request PR created as part of a history rewrite process type:feat New feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants