Skip to content

refactor: move Drive sync to requests-based REST transport - #12

Closed
Sinity wants to merge 7 commits into
masterfrom
feature/drive/rest-migration
Closed

Sinity wants to merge 7 commits into
masterfrom
feature/drive/rest-migration

Conversation

@Sinity

@Sinity Sinity commented Apr 7, 2026 •

Copy link
Copy Markdown
Owner

Summary

I replaced the Google Drive client-library integration with direct Drive v3 REST calls built on requests and AuthorizedSession. The main effect is a much smaller and more explicit transport layer: polylogue/drive.py no longer depends on googleapiclient.discovery.Resource, HttpError, or MediaIoBaseDownload, and the packaging story no longer needs the full Drive client stack. Fixed the fallout that surfaced while making that swap, including package discovery for polylogue.*, typed stats filtering during builds, and a console-auth fallback for environments where run_console() is absent. The end result is still the same user-facing Drive feature set, but the implementation is leaner and easier to reason about.

Motivation

The old Drive path hid a lot of complexity behind the generated Google client objects. That is convenient initially, but it couples the project to a large dependency surface, awkward packaging requirements, and library-specific exceptions/helpers. It also makes relatively simple operations — list files, get metadata, download media — look more magical than they need to be.

The branch history shows that I explored a packaging-only mitigation first. I dropped google-generativeai, then briefly split Drive dependencies into optional extras / separate Nix outputs. That reduced the default footprint a bit, but it did not address the deeper problem: we were still carrying the big client-library stack just to make a handful of Drive v3 calls. Once I switched the transport to direct REST requests, the separate “drive extras” experiment stopped being worth the cognitive overhead, so the branch collapses back to a simpler core dependency set.

The auth compatibility issue was another motivator. Relying on run_console() as though it were always present is brittle across auth library versions. Since I was already rewriting the transport, I took the chance to make console OAuth more explicit and resilient.

Changes by concern

1. Replace generated client objects with explicit REST helpers

polylogue/drive.py builds an AuthorizedSession and uses it to call the Drive REST API directly. The important pieces are:

  • _drive_get_json() for GET + JSON parsing
  • _raise_for_status() for normalized HTTP failure handling
  • list_children() / find_folder_id() / get_file_meta() built on those helpers
  • download_file() implemented via streaming iter_content()

Before, the code looked conceptually like this:

service.files().list(...).execute()
service.files().get(...).execute()
MediaIoBaseDownload(...)

Now it is closer to:

session.get(f"{DRIVE_BASE}/files", params=...)
session.get(f"{DRIVE_BASE}/files/{file_id}", params=...)
session.get(..., params={"alt": "media"}, stream=True)

That makes pagination, metadata fields, retry boundaries, and download streaming visible in our own code instead of being implicit in the client library.

2. Normalize errors and auth compatibility

I introduced DriveApiError so the rest of the code does not have to know about HttpError. The new exception carries a message, status code, and payload, which is enough for the transport layer and substantially easier to test/reason about later.

Added a manual console-flow fallback for auth stacks where run_console() is missing. That keeps the existing “authenticate in a terminal” workflow alive without pinning Polylogue to one exact auth-library version.

DriveClient.service catches transport/runtime failures from the new layer and translates them into user-facing banners / SystemExit, which keeps the interactive UX in line with the rest of the tool.

3. Simplify packaging around the new transport

pyproject.toml, flake.nix, and nix/devshell.nix all change here. The net effect is:

  • remove google-api-python-client
  • remove google-auth-httplib2
  • remove google-generativeai
  • add requests
  • keep google-auth-oauthlib for OAuth token handling

Collapsed the short-lived optional-drive packaging split that appeared mid-branch. Once Drive transport only depends on auth + requests, the extra complexity of separate polylogue-with-drive outputs and a dedicated drive shell no longer pays for itself.

Finally, I fixed the wheel packaging issue by broadening setuptools discovery from polylogue to polylogue.*; otherwise the importer subpackages disappear in built wheels.

4. Opportunistic fixes exposed by the refactor

Two smaller fixes landed because the transport/package rewrite made them visible:

  • parse_input_time_to_epoch() accepts numeric/date/datetime inputs, which fixes stats filtering failures in Nix build contexts that pass typed values.
  • the stats front-matter parser in cli.py falls through on failure instead of returning an empty dict for the whole aggregation.

These are not Drive features, but they were genuine regressions/paper cuts surfaced by running the tighter build path.

Testing

This branch does not add dedicated new tests for the REST transport itself. The existing pytest suite still runs via the flake build, and I fixed package discovery and stats parsing so those existing tests/package builds keep passing. The obvious gaps remain:

  • no transport-level tests for REST pagination or error payload mapping
  • no auth compatibility tests for missing run_console()
  • no large-file streaming download tests

Those are good follow-ups once the REST surface settles.

Notes

  • get_drive_service() is intentionally a session factory, not a Google Resource factory. Any internal code that expected service.files() semantics has to stay on the helper functions in polylogue/drive.py.
  • The optional-drive packaging experiment was useful as an interim checkpoint, but the final branch lands in a simpler place than it started.
  • The README no longer needs to describe Drive extras because Drive support is back in the core package with a much smaller dependency footprint.

@Sinity Sinity added type:refactor Code restructuring area:cli CLI area:pipeline Pipeline labels Apr 7, 2026
Copilot AI review requested due to automatic review settings April 7, 2026 11:33
@coderabbitai

coderabbitai Bot commented Apr 7, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This PR adds five provider documentation files describing ChatGPT, Claude.ai, Claude Code, Gemini, and OpenAI Codex import workflows, refactors the Google Drive client from googleapiclient to REST-based requests with custom error handling, updates build configs to remove Google dependencies, and enhances utility functions for broader type support.

Changes

Cohort / File(s) Summary
Provider Documentation
docs/providers/chatgpt.md, docs/providers/claude-ai.md, docs/providers/claude-code.md, docs/providers/gemini.md, docs/providers/openai-codex.md
Comprehensive documentation for five conversation export formats, detailing import strategies, Markdown rendering rules, attachment handling, and automation entry points for each provider.
Drive API Refactoring
polylogue/drive.py
Replaced googleapiclient.build with requests-based REST calls via google.auth.transport.requests.AuthorizedSession; introduced DriveApiError exception, added _run_console_flow() OAuth fallback, refactored all operations (list_children, find_folder_id, get_file_meta, download_file) to use REST endpoints, and updated get_drive_service() return type from service object to AuthorizedSession.
Drive Client Error Handling
polylogue/drive_client.py
Wrapped get_drive_service() call in try/except to catch RuntimeError and convert to user-facing SystemExit with appropriate messaging.
Dependency Management
flake.nix, nix/devshell.nix, pyproject.toml
Removed google-api-python-client, google-auth-httplib2, google-generativeai from runtime/dev dependencies; added requests; refactored Nix config to use shared baseDeps list and accept extraPythonPackages parameter.
Minor Updates
polylogue/cli.py, polylogue/util.py
cli.py: changed frontmatter load failure path to fall through to manual parser instead of short-circuiting. util.py: expanded parse_input_time_to_epoch to accept str, float, int, datetime.date, datetime.datetime with appropriate type handling.

Possibly Related Issues

  • Issue #11: Directly addressed by the Drive API refactoring—replaces googleapiclient with AuthorizedSession-based REST layer, introduces DriveApiError and console OAuth fallback, and removes Google client library dependencies as specified in the issue.

Poem

🐰 Five providers now documented with care,
Drive API refactored—requests in the air!
No more fat Google libs weighing us down,
Type-safe utilities wear a new crown. ✨

Estimated Code Review Effort

🎯 4 (Complex) | ⏱️ ~65 minutes

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 5.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 change: replacing Google Drive client library with requests-based REST transport, which is the primary refactoring across polylogue/drive.py, dependencies, and related infrastructure.
Description check ✅ Passed The pull request description is comprehensive and well-structured. It covers the summary, motivation, detailed changes by concern, testing notes, and additional context. All major sections from the template are present or appropriately adapted.

✏️ 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/drive/rest-migration

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

Refactors Polylogue’s Google Drive integration to use explicit Drive v3 REST calls over an authenticated requests transport (via AuthorizedSession), reducing dependency weight and making the transport/error boundaries more explicit. The PR also adjusts packaging/Nix build inputs to match the new dependency set and includes a couple of build/test-path fixes (typed stats time parsing + more robust front-matter fallback).

Changes:

  • Replace googleapiclient Drive client usage with direct REST helpers + streaming download in polylogue/drive.py.
  • Simplify dependencies and packaging discovery (Python + Nix) to drop the Drive client stack and include subpackages in wheels.
  • Improve stats time parsing and front-matter metadata fallback behavior; add provider documentation pages.

Reviewed changes

Copilot reviewed 12 out of 12 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
pyproject.toml Removes Google client deps, adds requests, and fixes setuptools package discovery for polylogue.*.
polylogue/util.py Extends parse_input_time_to_epoch to accept typed numeric/date/datetime inputs.
polylogue/drive.py Implements Drive REST transport, normalizes HTTP errors, and replaces client-library download/list/get calls.
polylogue/drive_client.py Improves UX when Drive dependencies are missing by translating import failures into banners/SystemExit.
polylogue/cli.py Makes stats front-matter loading fall back to a minimal parser rather than returning empty metadata on failure.
nix/devshell.nix Updates dev shell Python libs to match the new lighter dependency set; adds extraPythonPackages hook.
flake.nix Updates build inputs to drop heavy Google client libs and use a base dependency list for the app build.
docs/providers/openai-codex.md Adds documentation for importing Codex CLI sessions.
docs/providers/gemini.md Adds documentation for Gemini import/sync behavior.
docs/providers/claude-code.md Adds documentation for Claude Code session imports.
docs/providers/claude-ai.md Adds documentation for Claude.ai export handling.
docs/providers/chatgpt.md Adds documentation for ChatGPT export import workflow.
Comments suppressed due to low confidence (2)

polylogue/drive.py:62

  • _retry() currently retries on every exception, including DriveApiError for deterministic 4xx failures (e.g., 400/403/404). That can add unnecessary backoff delays and make interactive failures feel “hung.” Consider short-circuiting retries for DriveApiError with status < 500 except for 429 (and possibly 408).
    for i in range(retries):
        try:
            return fn()
        except Exception as e:
            last_err = e
            time.sleep(base_delay * (2 ** i))
    if last_err:
        raise last_err

polylogue/util.py:87

  • parse_input_time_to_epoch() treats naive datetime objects as UTC (sets tzinfo=UTC) but treats naive ISO datetime strings as local time (datetime.fromisoformat(...).timestamp()). This inconsistency can shift filtering results depending on whether callers pass typed datetimes vs strings. Consider normalizing naive parsed datetimes to UTC before calling timestamp(), similar to the datetime object branch.
    try:
        if re.match(r"^\d{4}-\d{2}-\d{2}$", s):
            dt = datetime.datetime.fromisoformat(s)
            return dt.replace(tzinfo=datetime.timezone.utc).timestamp()
        if s.endswith("Z"):
            s = s[:-1] + "+00:00"
        return datetime.datetime.fromisoformat(s).timestamp()
    except Exception:

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

Comment thread polylogue/drive.py
Comment on lines 44 to 63
@@ -35,18 +55,80 @@ def _retry(fn, *, retries: int = 3, base_delay: float = 0.5):
for i in range(retries):
try:
return fn()
except Exception as e: # HttpError or transport errors
except Exception as e:
last_err = e
time.sleep(base_delay * (2 ** i))
if last_err:
raise last_err
return 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.

_retry() can return None without ever invoking fn() when POLYLOGUE_RETRIES is set to 0 (range(0) never executes). Callers like _drive_get_json() then treat the result as a dict and will crash. Consider treating the env var as “number of retries after the first attempt” (i.e., always make at least one call) or clamp retries to >= 1.

Copilot uses AI. Check for mistakes.
Comment thread polylogue/drive.py
Comment on lines +206 to +213
resp = _drive_get_json(
session,
"files",
{
"q": f"mimeType='application/vnd.google-apps.folder' and name='{folder_name}' and trashed=false",
"fields": "files(id, name, modifiedTime)",
"pageSize": 50,
},

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 Drive query in find_folder_id() interpolates folder_name directly into a single-quoted q string. If folder_name contains a single quote, the query becomes invalid (and it also allows query injection via CLI-provided values). Escape quotes per Drive query rules (or otherwise sanitize) before building the q parameter.

Copilot uses AI. Check for mistakes.
Comment thread polylogue/drive.py
Comment on lines +66 to +128
def _raise_for_status(resp: requests.Response) -> None:
if resp.status_code < 400:
return
message = f"HTTP {resp.status_code}"
payload: Optional[Dict[str, Any]] = None
try:
payload = resp.json()
msg = payload.get("error", {}).get("message")
if isinstance(msg, str) and msg.strip():
message = msg
except Exception:
text = resp.text.strip()
if text:
message = text
raise DriveApiError(message, resp.status_code, payload)


def _authorized_session(creds: Credentials) -> AuthorizedSession:
return AuthorizedSession(creds)


def _run_console_flow(flow: InstalledAppFlow, *, verbose: bool) -> Credentials:
"""Console-mode auth fallback when InstalledAppFlow.run_console is unavailable."""
run_console = getattr(flow, "run_console", None)
if callable(run_console):
return run_console()

auth_url, _ = flow.authorization_url(prompt="consent")
prompt = (
"Open this link in your browser to authorize Polylogue:\n"
f" {auth_url}\n"
)
print(colorize(prompt, "magenta") if verbose else prompt)

try:
code = input(
colorize("Enter the authorization code: ", "cyan")
if verbose
else "Enter the authorization code: "
).strip()
except EOFError as exc:
raise RuntimeError("Authorization cancelled") from exc

if not code:
raise RuntimeError("Empty authorization code supplied.")

flow.fetch_token(code=code)
return flow.credentials


def _drive_get_json(session: AuthorizedSession, path: str, params: Dict[str, Any]) -> Dict[str, Any]:
url = f"{DRIVE_BASE}/{path}"

def call():
resp = session.get(url, params=params, timeout=60)
try:
_raise_for_status(resp)
return resp.json()
finally:
resp.close()

return _retry(call)

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 new REST transport helpers (_raise_for_status/_drive_get_json) and pagination/download logic are a significant behavior surface change, but there are still no unit tests exercising error mapping, pagination (nextPageToken), or download streaming. Since the repo already has pytest coverage, adding mocked AuthorizedSession/Response tests here would help prevent regressions.

Copilot uses AI. Check for mistakes.
Sinity added a commit that referenced this pull request Apr 7, 2026
Eliminate google-api-python-client, google-auth-httplib2, and
google-generativeai from the dependency tree. All Drive v3 access
now goes through requests + AuthorizedSession hitting REST endpoints
directly.

Core drive module (polylogue/drive.py):
- get_drive_service() returns AuthorizedSession instead of Resource
- New DriveApiError(message, status, payload) replaces HttpError
- download_file() uses streaming iter_content, not MediaIoBaseDownload
- _run_console_flow() provides manual OAuth fallback when
  run_console() is absent in newer google-auth versions
- require_google() centralizes import-failure gating with chained
  exception context

Drive client (polylogue/drive_client.py):
- service property surfaces missing-deps as SystemExit with banner

Packaging:
- pyproject.toml: drop 3 google deps, add requests; fix packages.find
  to include polylogue.* (was missing subpackages in wheel)
- flake.nix: extract baseDeps list, switch to pyproject=true, add
  setuptools/wheel as nativeBuildInputs
- nix/devshell.nix: restructure with let/in and extraPythonPackages
  parameter for extension

Opportunistic fixes:
- util.py: parse_input_time_to_epoch() accepts int/float/date/datetime
- cli.py: stats frontmatter parser falls through on failure instead
  of returning empty dict

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

Caution

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

⚠️ Outside diff range comments (1)
polylogue/cli.py (1)

1499-1529: ⚠️ Potential issue | 🔴 Critical

diff_enabled is undefined — causes NameError at runtime.

The variable diff_enabled is used on line 1528 but is never defined in run_sync_claude_code. Compare to run_sync_codex which correctly defines it on line 1425.

🐛 Proposed fix
     force = args.force
     prune = args.prune
+    diff_enabled = getattr(args, "diff", False)

     selected_paths: Optional[List[Path]] = None

Add after line 1507, similar to how it's done in run_sync_codex.

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

In `@polylogue/cli.py` around lines 1499 - 1529, In run_sync_claude_code,
diff_enabled is referenced but never defined; define it like in run_sync_codex
by reading the CLI flag and default setting (e.g., set diff_enabled = args.diff
or SETTINGS.diff_previews) and place this assignment after the other option
initializations (collapse/html/html_theme/force/prune) so
sync_claude_code_sessions receives a valid diff_enabled value.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@docs/providers/openai-codex.md`:
- Line 25: Update the docs sentence about `reasoning` payloads to clarify they
are skipped rather than explicitly filtered: change the line "Ignore encrypted
`reasoning` payloads until OpenAI exposes a readable form." to something like
"Unhandled `reasoning` payloads are skipped during import; explicit support will
be added when OpenAI exposes a readable form." This matches the behavior in
polylogue/importers/codex.py where only types 'message', 'function_call', and
'function_call_output' are processed and other types are implicitly skipped.

In `@polylogue/drive.py`:
- Around line 161-166: The token write block silently swallows failures
(token_path, creds.to_json), which hides permission/IO errors; replace the bare
except pass with logging: obtain a module logger (e.g.,
logging.getLogger(__name__)), catch Exception as e and log the failure
(logger.exception or logger.debug with the exception) including token_path and a
descriptive message so token persistence errors are visible for troubleshooting.
Ensure the logging call preserves the original exception stack trace.
- Around line 205-214: The code interpolates folder_name directly into the Drive
API q string (in the call to _drive_get_json), which allows single quotes in
folder names to break the query; sanitize/escape folder_name before building the
params (e.g., replace single quotes with backslash-escaped ones: folder_name =
folder_name.replace("'", "\\'")) and then use the escaped value in the q string
so the query cannot be injected or malformed.

In `@polylogue/util.py`:
- Around line 66-69: The try/except around the float(s) conversion is too
broad—replace the broad except Exception with narrower exceptions (catch
ValueError and TypeError) so only conversion-related errors are handled; locate
the try block that returns float(s) in polylogue/util.py and change the
exception clause to catch ValueError and TypeError and still return None on
those cases.

---

Outside diff comments:
In `@polylogue/cli.py`:
- Around line 1499-1529: In run_sync_claude_code, diff_enabled is referenced but
never defined; define it like in run_sync_codex by reading the CLI flag and
default setting (e.g., set diff_enabled = args.diff or SETTINGS.diff_previews)
and place this assignment after the other option initializations
(collapse/html/html_theme/force/prune) so sync_claude_code_sessions receives a
valid diff_enabled value.
🪄 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: 51eea338-a13e-4513-831a-ec7a3ee9b9c2

📥 Commits

Reviewing files that changed from the base of the PR and between 2efba0b and 208e317.

📒 Files selected for processing (12)
  • docs/providers/chatgpt.md
  • docs/providers/claude-ai.md
  • docs/providers/claude-code.md
  • docs/providers/gemini.md
  • docs/providers/openai-codex.md
  • flake.nix
  • nix/devshell.nix
  • polylogue/cli.py
  • polylogue/drive.py
  • polylogue/drive_client.py
  • polylogue/util.py
  • pyproject.toml

- Parse the JSONL stream, skipping boilerplate rows like `<user_instructions>` or `<environment_context>` that are repeated in every file.
- Normalise `response_item:type == "message"` rows into user/assistant turns.
- Pair `function_call` entries with their corresponding `function_call_output` (linked via `call_id`). Render them as a single tool block with arguments and results; spill oversized payloads into `_attachments/` while keeping a short inline preview.
- Ignore encrypted `reasoning` payloads until OpenAI exposes a readable form.

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

Clarify the handling of reasoning payloads.

The documentation states these are "ignored," but examining polylogue/importers/codex.py (lines 74-139 in context), the code doesn't explicitly filter reasoning types—it only processes known types (message, function_call, function_call_output) and implicitly skips unrecognized ones. This is functionally correct but could be misleading if OpenAI later makes reasoning readable and users expect explicit handling.

Consider rephrasing to: "Unhandled reasoning payloads are skipped during import; explicit support will be added when OpenAI exposes a readable form."

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

In `@docs/providers/openai-codex.md` at line 25, Update the docs sentence about
`reasoning` payloads to clarify they are skipped rather than explicitly
filtered: change the line "Ignore encrypted `reasoning` payloads until OpenAI
exposes a readable form." to something like "Unhandled `reasoning` payloads are
skipped during import; explicit support will be added when OpenAI exposes a
readable form." This matches the behavior in polylogue/importers/codex.py where
only types 'message', 'function_call', and 'function_call_output' are processed
and other types are implicitly skipped.

Comment thread polylogue/drive.py
Comment on lines 161 to 166
try:
token_path.parent.mkdir(parents=True, exist_ok=True)
with open(token_path, "w") as f:
with open(token_path, "w", encoding="utf-8") as f:
f.write(creds.to_json())
except Exception:
pass

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 logging token write failures instead of silently passing.

If token persistence fails, users won't know why they're repeatedly prompted for authentication. At minimum, a debug-level log would help troubleshoot permission issues.

🔧 Proposed fix to add logging
             try:
                 token_path.parent.mkdir(parents=True, exist_ok=True)
                 with open(token_path, "w", encoding="utf-8") as f:
                     f.write(creds.to_json())
-            except Exception:
-                pass
+            except Exception as exc:
+                if verbose:
+                    print(colorize(f"Warning: could not save token: {exc}", "yellow"))
🧰 Tools
🪛 Ruff (0.15.9)

[error] 165-166: try-except-pass detected, consider logging the exception

(S110)


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

(BLE001)

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

In `@polylogue/drive.py` around lines 161 - 166, The token write block silently
swallows failures (token_path, creds.to_json), which hides permission/IO errors;
replace the bare except pass with logging: obtain a module logger (e.g.,
logging.getLogger(__name__)), catch Exception as e and log the failure
(logger.exception or logger.debug with the exception) including token_path and a
descriptive message so token persistence errors are visible for troubleshooting.
Ensure the logging call preserves the original exception stack trace.

Comment thread polylogue/drive.py
Comment on lines 205 to +214
try:
resp = _retry(lambda: service.files().list(
q=f"mimeType='application/vnd.google-apps.folder' and name='{folder_name}' and trashed=false",
fields="files(id, name, modifiedTime)",
pageSize=50,
).execute())
resp = _drive_get_json(
session,
"files",
{
"q": f"mimeType='application/vnd.google-apps.folder' and name='{folder_name}' and trashed=false",
"fields": "files(id, name, modifiedTime)",
"pageSize": 50,
},
)

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

Escape folder_name to prevent query injection.

The folder_name is directly interpolated into the Drive API query string. If the name contains single quotes, it could break the query or cause unexpected behavior.

🛡️ Proposed fix to escape folder name
+def _escape_query_string(value: str) -> str:
+    """Escape single quotes for Drive API query strings."""
+    return value.replace("\\", "\\\\").replace("'", "\\'")
+
+
 def find_folder_id(session, folder_name: str) -> Optional[str]:
     cached = get_cached_folder_id(folder_name)
     # ... existing cache validation ...
     try:
+        escaped_name = _escape_query_string(folder_name)
         resp = _drive_get_json(
             session,
             "files",
             {
-                "q": f"mimeType='application/vnd.google-apps.folder' and name='{folder_name}' and trashed=false",
+                "q": f"mimeType='application/vnd.google-apps.folder' and name='{escaped_name}' and trashed=false",
                 "fields": "files(id, name, modifiedTime)",
                 "pageSize": 50,
             },
         )
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/drive.py` around lines 205 - 214, The code interpolates folder_name
directly into the Drive API q string (in the call to _drive_get_json), which
allows single quotes in folder names to break the query; sanitize/escape
folder_name before building the params (e.g., replace single quotes with
backslash-escaped ones: folder_name = folder_name.replace("'", "\\'")) and then
use the escaped value in the q string so the query cannot be injected or
malformed.

Comment thread polylogue/util.py
Comment on lines +66 to +69
try:
return float(s)
except Exception:
return 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.

🧹 Nitpick | 🔵 Trivial

Consider narrowing the exception type.

The broad except Exception on the float(s) conversion could mask unexpected errors. Since s is already typed as int | float at this point, conversion should only fail for unusual subclass scenarios.

🔧 Optional: Narrow exception handling
     if isinstance(s, (int, float)):
         try:
             return float(s)
-        except Exception:
+        except (TypeError, ValueError):
             return None
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try:
return float(s)
except Exception:
return None
try:
return float(s)
except (TypeError, ValueError):
return None
🧰 Tools
🪛 Ruff (0.15.9)

[warning] 68-68: 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/util.py` around lines 66 - 69, The try/except around the float(s)
conversion is too broad—replace the broad except Exception with narrower
exceptions (catch ValueError and TypeError) so only conversion-related errors
are handled; locate the try block that returns float(s) in polylogue/util.py and
change the exception clause to catch ValueError and TypeError and still return
None on those cases.

@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/drive/rest-migration branch April 9, 2026 23:02
Sinity added a commit that referenced this pull request Apr 22, 2026
Eliminate google-api-python-client, google-auth-httplib2, and
google-generativeai from the dependency tree. All Drive v3 access
now goes through requests + AuthorizedSession hitting REST endpoints
directly.

Core drive module (polylogue/drive.py):
- get_drive_service() returns AuthorizedSession instead of Resource
- New DriveApiError(message, status, payload) replaces HttpError
- download_file() uses streaming iter_content, not MediaIoBaseDownload
- _run_console_flow() provides manual OAuth fallback when
  run_console() is absent in newer google-auth versions
- require_google() centralizes import-failure gating with chained
  exception context

Drive client (polylogue/drive_client.py):
- service property surfaces missing-deps as SystemExit with banner

Packaging:
- pyproject.toml: drop 3 google deps, add requests; fix packages.find
  to include polylogue.* (was missing subpackages in wheel)
- flake.nix: extract baseDeps list, switch to pyproject=true, add
  setuptools/wheel as nativeBuildInputs
- nix/devshell.nix: restructure with let/in and extraPythonPackages
  parameter for extension

Opportunistic fixes:
- util.py: parse_input_time_to_epoch() accepts int/float/date/datetime
- cli.py: stats frontmatter parser falls through on failure instead
  of returning empty dict
@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. 1 finding(s) confirmed still present → tracked in #550. 5 finding(s) confirmed fixed/stale.

@Sinity

Sinity commented May 1, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

💡 Codex Review

wanted = {sanitize_filename(item.name or item.id or "") for item in items}
to_delete = compute_prune_paths(options.output_dir, wanted)

P1 Badge Prevent prune from deleting chats outside synced subset

Build the prune allowlist from the full remote chat set, not from items (successful writes). Right now wanted is derived from items, so any chat skipped due to filters (--since/--until, name filter, interactive selection) or transient download/parse failures is treated as stale and its local .md/_attachments paths are deleted when --prune is enabled. This can remove valid exports that still exist in Drive after a partial sync run.


fname = sanitize_filename(meta_att.get("name", att_id))
local_path = attachments_dir / fname
if not dry_run:
if force or not local_path.exists():
ok = drive.download_attachment(att_id, local_path)

P1 Badge Disambiguate attachment filenames before writing to disk

Use a unique on-disk name per attachment ID instead of only meta_att['name']. In the current logic, two different Drive attachments with the same filename within one conversation both map to the same local_path, so the later download overwrites the earlier file and both rendered links point to ambiguous content. This silently corrupts attachment exports for common duplicate names like image.png or notes.txt.

ℹ️ 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".

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 added a commit that referenced this pull request Aug 19, 2026
## Summary

Five small, independent quality fixes batched into one PR (H5 quality
sweep,
`.agent/campaigns/2026-08-overhaul/` queue row #12): two real code fixes
with
red-before/green-after tests (`polylogue-f47j`, `polylogue-iuyr`), one
narrowing fix for a mislabelled-session bug found by a parallel audit
(`polylogue-omsw` class), and two beads (`polylogue-6krh`,
`polylogue-es7b`)
that turned out to already be fully fixed and tested on `master` when
investigated — verified rather than assumed.

## Problem

- **polylogue-f47j**: `registry.promote_cluster`'s samples-based
candidate
  generator (`generate_schema_from_samples`) never received a
  `PrivacyConfig`, unlike the full `generate` pipeline's
`_generate_cluster_schema`. An explicit deny rule supplied by a caller
was
silently ignored on the samples path — the same class of gap that let a
  low-cardinality UUID-shaped field record its literal per-record values
  verbatim during a 2026-07-29 promotion (caught after the fact by
  `devtools schema_audit`, fixed at the time by manual annotation
  stripping, not by this fix). **Cold review on an earlier revision of
  this PR caught that the initial fix only plumbed `privacy_config`
  through the library function — it was still unreachable from
`devtools schema-promote`, the actual command a live promotion runs, so
every real run would have stayed exactly as unredacted as before this PR
  until that was completed** (see Solution and the second commit below).
  The compensating control that actually caught the 2026-07-29 leak
(`devtools schema_audit`'s privacy-guard check) still runs in no gate —
  tracked separately as polylogue-32pwq, not in this PR's scope.
- **polylogue-iuyr**: `compute_session_cost`'s per-model loop called
  `estimate_cost()` for every model with a normalized name, but
`estimate_cost()` silently returns `0.0` when the pricing catalog has no
entry for that model. A model with real, nonzero reported/estimated
tokens
but no catalog price (e.g. `claude-opus-5`, a confirmed live catalog
gap)
  surfaced as `confidence='reported'` with `total_api_cost_usd=0.0` —
  indistinguishable from a provider that genuinely billed zero.
- **polylogue-omsw class (Hermes skill templates)**: the Hermes watch
source
  recursively scans its entire `~/.hermes` home directory (not just a
  sessions subtree), so skill prompt-prefill templates under
  `optional-skills/**/templates/*.json` reached artifact classification
tagged `provider="hermes"`. Their bare `{"role", "content"}` array shape
  satisfied the generic `looks_like_record_entry` heuristic in
`_classify_list` and got claimed as a session, then quarantined when it
failed to parse ("session artifact produced no materializable
sessions").
Found by a parallel dyica-classification audit (2026-08-19, bucket B6),
  both live template files still on disk for testing.
- **polylogue-6krh / polylogue-es7b**: both were re-investigated per the
dispatch and found to already be fully fixed **and tested** on `master`
  (see disposition matrix below) — no code changes made in this PR for
  either.

## Solution

- `polylogue/schemas/generation/schema_builder.py`:
`generate_schema_from_samples`
gains a `privacy_config` parameter, threaded into its `_annotate_schema`
call (the same redaction path `_generate_cluster_schema` already used).
- `polylogue/schemas/tooling_registry.py`: `promote_cluster` gains the
same
  `privacy_config` parameter and forwards it.
- `polylogue/schemas/operator/registry.py`:
`SchemaRegistryLike.promote_cluster`
protocol updated to match (plus `tests/unit/scenarios/test_corpus.py`'s
  fake registry, to keep mypy's Protocol-conformance check green).
- **Completing the wiring to the real caller** (added after cold
review):
`polylogue/schemas/operator/models.py`'s `SchemaPromoteRequest` gains a
  `privacy_config: JSONDocument | None` field (the same shape
`SchemaInferRequest` already carries);
`polylogue/schemas/operator/inference.py`'s
  `promote_schema_cluster` forwards it through `_privacy_config()` (now
  also exported as `privacy_config_from_payload` for reuse) into
  `registry.promote_cluster()`; `devtools/schema_promote.py` gains
  `--privacy`/`--privacy-config` flags, reusing
  `build_schema_privacy_config` — the exact same resolution the full
  `generate` pipeline's equivalent flags already use, not a parallel
  config path.
- `polylogue/archive/semantic/cost_compute.py`: the per-model breakdown
loop
now checks `pricing_catalog_source(norm)` before trusting a
`'reported'`/
  `'estimated'` confidence; a model with no catalog entry downgrades to
`'unknown'` regardless of token evidence, so `estimate_cost()`'s silent
  `0.0` can never be read as a confident zero.
- `polylogue/archive/artifact_taxonomy/runtime.py`: `_classify_list`
narrows
  the Hermes branch — a list-shaped payload under `provider="hermes"` is
  only session-eligible when it's a genuine ATOF event stream (the one
list-shaped Hermes source class; state.db/ATIF/session-snapshots are all
single JSON documents). Any other Hermes list payload is refused
outright
  instead of falling through to the generic `looks_like_record_stream`
  heuristic.

Alternative considered and rejected for the Hermes fix: narrowing the
Hermes *parser* predicates (`polylogue/sources/parsers/hermes*.py`), as
originally suggested. Traced the actual claim path instead — the parsers
were never reached; `archive/artifact_taxonomy/runtime.py`'s generic
`_classify_list` (shared by every provider) is what admitted the
template as
a session, so that is where the fix belongs.

## Verification

- `devtools test
tests/unit/schemas/test_promote_cluster_privacy_config.py` — 4 passed
(f47j library-level plumbing; red confirmed by reverting the source
change and re-running before committing).
- `devtools test tests/unit/core/test_operator_inference.py` — 6 passed,
including
`test_promote_cluster_with_samples_honors_privacy_config_through_the_real_operator_route`
(f47j, operator-route completion; red confirmed — reverting the wiring
made `SchemaPromoteRequest(..., privacy_config=...)` raise `TypeError:
unexpected keyword argument`, i.e. the field genuinely didn't exist
before this fix). Also ran `tests/unit/core/test_operator_models.py`,
`tests/unit/cli/test_operator_support_runtime.py`,
`tests/unit/schemas/test_operator_commit.py`,
`tests/unit/schemas/test_promotion_audit_privacy_guard.py`,
`tests/unit/schemas/test_promotion_monotonicity.py` — 38 passed total,
no regressions.
- `devtools test tests/unit/core/test_cost_compute.py` — 10 passed
(iuyr; red confirmed the same way).
- `devtools test tests/unit/sources/test_artifact_taxonomy.py` — 19
passed (Hermes fix; red confirmed the same way, plus the ATOF
anti-over-narrow twin passes both before and after).
- `devtools test` across every Hermes-touching test file (parsers,
dispatch, live watcher/batch, storage, daemon) — 880 passed, no
regressions.
- `devtools verify --quick` — clean (format + lint + mypy +
render-all-check + layering + schema policy + promotion audit).
- Full `devtools verify` **withheld**: this worktree's testmon graph
would need a full bootstrap (~45 min, first run in a freshly-provisioned
lane venv) that dies with the worktree at merge time — per the
digest-drift/lane-lifecycle policy, that cost buys nothing the
coordinator's own terminal verify at merge doesn't already provide. The
four focused suites above plus `--quick` are the substitute gate for
this PR; the coordinator's merge-time `devtools workspace merge` /
terminal verify is the release-baseline attestation of record.

## Bead disposition matrix

| Bead | Disposition | Evidence | Notes |
| --- | --- | --- | --- |
| polylogue-f47j | **SATISFIED** — close-candidate | commits 5bb08f4,
dc8dd06; `tests/unit/schemas/test_promote_cluster_privacy_config.py`,
`tests/unit/core/test_operator_inference.py::test_promote_cluster_with_samples_honors_privacy_config_through_the_real_operator_route`
| All three layers now land: (1) `privacy_config` threaded through the
library's samples path, (2) `promotion_audit`'s `check_privacy_guards`
wiring (AC #2) was already present on `master` before this PR — verified
live, not assumed, (3) the operator-route wiring (`SchemaPromoteRequest`
→ `promote_schema_cluster` → `devtools schema-promote --privacy`) that a
cold review found missing from the first revision — without it the
library fix was unreachable from any real promotion. |
| polylogue-iuyr | **SATISFIED** — close-candidate | commit 8aa2629;
`tests/unit/core/test_cost_compute.py::test_catalog_gap_model_with_real_tokens_is_not_a_confident_zero`
| Catalog-gap models now downgrade to `unknown` confidence instead of a
confident `$0.00`. |
| polylogue-6krh | **SATISFIED, no diff in this PR** — close-candidate |
`polylogue/sources/live/cursor.py:_sync_convergence_debt_to_ops` (writes
`status='deferred'` for deliberate deferrals); both `batch.py` deferral
call sites already pass `deferred=True`; all five reader/alert surfaces
named in the bead (`health.py`, `status.py`, cli `status.py`,
`api/archive.py`, `metrics.py`) already track
`failed_count`/`deferred_count` separately;
`tests/unit/sources/test_convergence_debt_deferred_vocabulary.py` covers
the full writer→reader chain end to end. This was PR #3621, already
merged. Remaining scope per the bead's own design note is **post-deploy
live verification only** (not code) plus the t0m73 vocabulary-honesty
registry check, which the bead explicitly says to note rather than
build. Not something this PR can evidence from a worktree. |
| polylogue-es7b | **PARTIAL** — item (a) only, bead stays open |
`polylogue/storage/embeddings/materialization.py`'s exception handler
(fallback to `Origin.UNKNOWN_EXPORT` sentinel,
`record_embedding_failure` always called);
`tests/unit/storage/test_embedding_contracts.py::test_archive_failure_ledger_survives_origin_lookup_failure`
| Item (a) (the one this sweep was scoped to) is already fixed and
tested on `master`, no diff in this PR. Items (b)/(c)/(d) from the
bead's own evidence (`write_coordinator.py` detached-writer counter,
`RuntimeError` suppress potential hang, `sampling_db.py`
missing-tier-file warning) are untouched and out of scope for this sweep
— no successor bead exists yet for those; **not included in the machine
pr-scope carrier below** since a partial disposition requires a linked
successor I'm not able to create from a read-only lane. Coordinator:
file a successor for (b)/(c)/(d) before considering this bead closeable.
|
| polylogue-omsw | **Referenced, not dispositioned** | commit c8e9f22
| Ref polylogue-omsw — this PR fixes one instance of the same
artifact-misclassification class the bead already tracks (Hermes skill
templates, dyica classification 2026-08-19 bucket B6), added as scope
creep by the coordinator mid-PR. The bead's own scope
(tool-result/journal sidecars, file-history-snapshot, codex-database
misclassification) is broader and untouched here — do not close
polylogue-omsw from this PR. |

The machine-readable carrier below covers only `polylogue-f47j` and
`polylogue-iuyr` (the two beads this PR both mutates code for and can
satisfy without a successor). `polylogue-6krh` and `polylogue-es7b` are
evidenced in prose above rather than the typed carrier, since satisfying
or
partial-closing them accurately would require either a diff this PR
doesn't
carry (6krh — already fixed elsewhere) or a successor Bead this lane
cannot
create (es7b's residual items b/c/d).

<!-- polylogue-pr-scope:v2
{
  "assigned_beads": [
    "polylogue-f47j",
    "polylogue-iuyr"
  ],
  "dispositions": [
    {
      "bead_id": "polylogue-f47j",
      "disposition": "satisfied",
      "evidence": [
        {
          "kind": "commit",
          "ref": "5bb08f4fe"
        },
        {
          "kind": "commit",
          "ref": "dc8dd062b"
        },
        {
          "kind": "test",
"ref": "tests/unit/schemas/test_promote_cluster_privacy_config.py"
        },
        {
          "kind": "test",
"ref":
"tests/unit/core/test_operator_inference.py::test_promote_cluster_with_samples_honors_privacy_config_through_the_real_operator_route"
        }
      ],
      "successors": []
    },
    {
      "bead_id": "polylogue-iuyr",
      "disposition": "satisfied",
      "evidence": [
        {
          "kind": "commit",
          "ref": "8aa262901"
        },
        {
          "kind": "test",
"ref":
"tests/unit/core/test_cost_compute.py::test_catalog_gap_model_with_real_tokens_is_not_a_confident_zero"
        }
      ],
      "successors": []
    }
  ],
  "mutated_beads": [],
"scope_digest":
"8bfb7aa6968f56d6b00d47cebabfa8afbac9f613975abaa524fc6cd7a5273511",
  "scope_kind": "bead",
  "version": 2
}
-->
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 faux-pull-request PR created as part of a history rewrite process type:refactor Code restructuring

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants