Skip to content

fix: aggregate small fixes from adversarial audit (waves 1+2) - #489

Merged
Sinity merged 4 commits into
masterfrom
feature/fix/aggregate-small-fixes
Apr 26, 2026
Merged

Sinity merged 4 commits into
masterfrom
feature/fix/aggregate-small-fixes

Conversation

@Sinity

@Sinity Sinity commented Apr 26, 2026 •

Copy link
Copy Markdown
Owner

Summary

35 fixes from a comprehensive 27-agent adversarial audit. Every fix is small-scope (1-15 lines) and independently verifiable.

Problem

Two waves of adversarial audit (15 + 12 specialized agents reading 500+ source files) surfaced ~50 findings. The critical and high-severity ones were filed as individual issues (#466-#487). This PR bundles all the small-scope, low-risk fixes that remain.

Solution

35 fixes across these categories:

Parsers — str() guard on Role.normalize() inputs prevents AttributeError on non-string role values (fixes #469)

Hashing — NFC normalization in _normalize_for_hash(), sentinel tokens in attachment_seed() prevent field-shift collisions, attachment SHA-256 digest included in content hash

Storage — FTS trigger DDL fixed to match 6-column schema (fixes #467), triggers use rowid instead of UNINDEXED columns (fixes #484), COALESCE(excluded.metadata, conversations.metadata) preserves user tags on content change (fixes #473), quick_readiness_summary uses correct db_path(), redundant index removed, misleading comment fixed

CLI — open_verb uses candidate-concatenation pattern matching show_verb, show_verb added (was absent on master per #422), doctor→check with hidden alias, fail() unified to click.echo("Error: ..."), empty archive shows onboarding hint, export help documents provider:id

MCP — _clamp_limit upper bound (1000), get_stats_by uses Literal type, resolve_id strict flag for destructive ops, bulk_tag_conversations item-count limits + batch TX

Rendering — heading escape covers all levels (# through ###### ), CSV injection prevention with _csv_safe(), plaintext renderer added

Config/security — dead fts_enabled removed, max_length falsy fix, XDG path dedup, POLYLOGUE_FORCE_PLAIN respected in logging, db/blob chmod 0o600, manifest path leak fixed

Build — h2 added to Nix deps for httpx[http2], hatch_build.py sdist fix, typing_extensions→stdlib typing (18 files)

Products — profile_bucket_day timezone-aware, records_provenance ISO parse before compare, pricing.py model prefix sorted by length, name added to privacy content-field denylist

Dead code — cli/commands/embed.py deleted (own docstring admitted it was orphaned)

Verification

devtools verify
  ruff format ... ok
  ruff check ... ok
  mypy ... ok (17.0s)
  render-all ... ok (45.4s)
  verify-topology ... ok
  verify-file-budgets ... ok
  verify-test-ownership ... ok
  verify-migrations ... ok
  verify-cross-cuts ... ok

Closes #488

🤖 Generated with Claude Code

Summary by CodeRabbit

Release Notes

  • New Features

    • Added plaintext conversation output format supporting markdown stripping
    • Enhanced mutation tools with strict ID resolution and bulk tag operations
    • Improved CLI verb behavior for show and open commands
  • Bug Fixes

    • Fixed CSV formula injection vulnerability with cell-content sanitization
    • Corrected markdown header escaping across all heading levels
    • Fixed timezone handling in timestamp normalization
    • Improved conversation metadata preservation during updates
    • Hardened SQLite database file permissions
  • Documentation

    • Updated CLI reference wording for default behavior descriptions
  • Refactor

    • Standardized TypedDict imports across modules
    • Enhanced ID resolution with strict-mode support
    • Improved privacy filter configuration and field classification

@coderabbitai

coderabbitai Bot commented Apr 26, 2026 •

Copy link
Copy Markdown

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 830b16e7-efaa-429a-aaf7-e76bf89e6213

📥 Commits

Reviewing files that changed from the base of the PR and between 028cd58 and ec13360.

📒 Files selected for processing (66)
  • docs/cli-reference.md
  • docs/plans/topology-target.yaml
  • docs/verification-catalog.md
  • flake.nix
  • hatch_build.py
  • polylogue/archive_products.py
  • polylogue/artifacts.py
  • polylogue/cli/commands/embed.py
  • polylogue/cli/commands/export.py
  • polylogue/cli/helper_summary.py
  • polylogue/cli/helper_support.py
  • polylogue/cli/query_verbs.py
  • polylogue/config.py
  • polylogue/lib/embeddings/stats.py
  • polylogue/lib/pricing.py
  • polylogue/lib/session_payload_documents.py
  • polylogue/lib/timestamps.py
  • polylogue/logging.py
  • polylogue/mcp/payloads.py
  • polylogue/mcp/server_mutation_tools.py
  • polylogue/mcp/server_prompts.py
  • polylogue/mcp/server_support.py
  • polylogue/mcp/server_tools.py
  • polylogue/pipeline/ids.py
  • polylogue/pipeline/payload_types.py
  • polylogue/pipeline/run_finalization.py
  • polylogue/pipeline/semantic_capture.py
  • polylogue/pipeline/services/acquisition_records.py
  • polylogue/pipeline/services/indexing.py
  • polylogue/pipeline/services/ingest_batch.py
  • polylogue/pipeline/services/ingest_worker.py
  • polylogue/protocols.py
  • polylogue/readiness.py
  • polylogue/rendering/core_markdown.py
  • polylogue/rendering/formatting.py
  • polylogue/rendering/renderers/__init__.py
  • polylogue/rendering/renderers/plaintext.py
  • polylogue/schemas/privacy.py
  • polylogue/schemas/privacy_config.py
  • polylogue/site/publication_flow.py
  • polylogue/sources/assembly.py
  • polylogue/sources/drive_gateway.py
  • polylogue/sources/parsers/chatgpt.py
  • polylogue/sources/parsers/claude_common.py
  • polylogue/storage/backends/async_sqlite.py
  • polylogue/storage/backends/async_sqlite_archive.py
  • polylogue/storage/backends/connection.py
  • polylogue/storage/backends/queries/conversations_identity.py
  • polylogue/storage/backends/queries/conversations_writes.py
  • polylogue/storage/backends/queries/stats.py
  • polylogue/storage/backends/query_store_archive.py
  • polylogue/storage/backends/schema_ddl_actions.py
  • polylogue/storage/backends/schema_ddl_archive.py
  • polylogue/storage/backends/schema_ddl_product_profiles.py
  • polylogue/storage/blob_store.py
  • polylogue/storage/cursor_state.py
  • polylogue/storage/fts_lifecycle.py
  • polylogue/storage/query_models.py
  • polylogue/storage/repository_archive_conversations.py
  • polylogue/storage/repository_writes.py
  • polylogue/storage/run_state.py
  • polylogue/storage/session_product_runtime.py
  • polylogue/surface_payloads.py
  • tests/unit/cli/test_embed.py
  • tests/unit/core/test_config.py
  • tests/unit/ui/test_ui_visual.py

📝 Walkthrough

Walkthrough

Applies ~40 targeted bug fixes from an adversarial audit across parser type-safety, timezone handling, FTS trigger DDL corrections, file permission hardening, typing imports modernization, CLI verb behavior refinements, and removal of obsolete modules.

Changes

Cohort / File(s) Summary
Parser Type-Safety
polylogue/sources/parsers/chatgpt.py, polylogue/sources/parsers/claude_common.py
Add str() wrapping around raw role values before normalization to prevent AttributeError crashes on non-string JSON types.
Timezone & Provenance Handling
polylogue/archive_products.py
profile_bucket_day() now converts naive datetimes to UTC before extracting date; records_provenance parses ISO-8601 timestamps into timezone-aware datetimes and computes max using datetime objects before outputting ISO format.
CLI Command Verbs & Help
polylogue/cli/query_verbs.py, polylogue/cli/commands/export.py
Redefine show_verb to use full-content output with provider:id shortcut logic; update open_verb to remove print-path option restriction; document conversation_id provider:id-prefix format in export help.
CLI Output & Support
polylogue/cli/helper_summary.py, polylogue/cli/helper_support.py
Add onboarding message and inbox path hint when archive has no conversations; emit standardized error messages to stderr before exit.
Markdown & CSV Rendering
polylogue/rendering/core_markdown.py, polylogue/rendering/formatting.py
Extend heading escape to levels 1–6 (not just level 2); add CSV formula-injection prevention by prefixing cells starting with =, +, -, @ with '.
Plaintext Renderer
polylogue/rendering/renderers/plaintext.py, polylogue/rendering/renderers/__init__.py
Introduce new PlaintextRenderer with markdown stripping; register plaintext format and export new renderer class.
FTS Schema & Triggers
polylogue/storage/backends/schema_ddl_actions.py, polylogue/storage/backends/schema_ddl_product_profiles.py, polylogue/storage/fts_lifecycle.py
Change FTS DELETE/UPDATE triggers to use rowid instead of unindexed content columns; fix action-event trigger DDL to map correct columns matching 6-column schema.
Metadata Preservation on Upsert
polylogue/storage/backends/queries/conversations_writes.py, polylogue/pipeline/services/ingest_batch.py
Use COALESCE(excluded.metadata, conversations.metadata) to preserve user-set tags when conversation content changes; update comment to clarify WHERE clause behavior.
Query ID Resolution
polylogue/storage/backends/queries/conversations_identity.py, polylogue/storage/backends/async_sqlite_archive.py, polylogue/storage/backends/query_store_archive.py, polylogue/storage/repository_archive_conversations.py, polylogue/protocols.py
Add optional keyword-only strict flag to resolve_id methods; when enabled, exact ID match is required (no prefix fallback).
MCP Mutation Tools & Support
polylogue/mcp/server_mutation_tools.py, polylogue/mcp/server_support.py, polylogue/mcp/server_tools.py
Resolve conversation IDs strictly before mutations; validate bulk-tag input sizes and use single bulk_add_tags call; add upper bound (1000) to _clamp_limit; restrict group_by to literal values.
Tag Management
polylogue/storage/repository_writes.py
Add input validation to add_tag (empty/length checks); introduce new bulk_add_tags async method with transaction scope and change tracking.
File Permission Hardening
polylogue/storage/backends/async_sqlite.py, polylogue/storage/backends/connection.py, polylogue/storage/blob_store.py
Apply chmod(0o600) to SQLite database and blob files at initialization, connection acquisition, and write operations.
Typing Modernization
polylogue/lib/embeddings/stats.py, polylogue/lib/session_payload_documents.py, polylogue/mcp/payloads.py, polylogue/mcp/server_prompts.py, polylogue/pipeline/payload_types.py, polylogue/pipeline/run_finalization.py, polylogue/pipeline/semantic_capture.py, polylogue/pipeline/services/acquisition_records.py, polylogue/pipeline/services/indexing.py, polylogue/pipeline/services/ingest_worker.py, polylogue/sources/assembly.py, polylogue/sources/drive_gateway.py, polylogue/storage/backends/queries/stats.py, polylogue/storage/cursor_state.py, polylogue/storage/query_models.py, polylogue/storage/run_state.py, polylogue/storage/session_product_runtime.py, polylogue/surface_payloads.py
Switch TypedDict import source from typing_extensions to standard-library typing across 18 modules.
Configuration & Paths
polylogue/config.py, polylogue/privacy_config.py, polylogue/schemas/privacy.py
Remove dead fts_enabled field from IndexConfig; import config_root() instead of duplicating XDG logic; fix max_length coercion to preserve explicit values.
Logging & Environment
polylogue/logging.py
Respect POLYLOGUE_FORCE_PLAIN environment variable to disable structlog color output.
Pricing & Model Matching
polylogue/lib/pricing.py
Sort PRICING dict keys by length descending for longest-prefix-first matching instead of iteration order.
Timestamp Parsing
polylogue/lib/timestamps.py
Add early rejection for Python repr-form strings (starting with {, [, () to prevent spurious parsing attempts.
Raw Archive Schema
polylogue/storage/backends/schema_ddl_archive.py
Remove redundant idx_raw_conv_source index; keep filtered compound index idx_raw_conv_source_mtime.
Readiness & Database Paths
polylogue/readiness.py
Use polylogue.paths.db_path() instead of hardcoded archive_root / "polylogue.db" for readiness probe.
Site Publication
polylogue/site/publication_flow.py
Normalize manifest output_dir to "." to avoid exposing absolute paths in published records.
Build & Packaging
flake.nix, hatch_build.py
Add h2 runtime dependency for httpx HTTP/2 support; conditionally preserve _build_info.py when POLYLOGUE_SDIST_BUILD is set.
Hash Normalization
polylogue/pipeline/ids.py
Apply NFC Unicode normalization to all string scalars in hash inputs; include null fields as literal "<null>" in attachment seeds; add per-attachment "digest" attribute from provider_meta SHA256.
Module Removal & Dead Code
polylogue/cli/commands/embed.py
Delete orphaned embed helper module (wrapper functions previously only used by tests).
Artifact & Verification Metadata
polylogue/artifacts.py, docs/plans/topology-target.yaml, docs/verification-catalog.md
Update embedding-status artifact code reference to point to polylogue.cli.embed_stats.show_embedding_stats; update topology projection and verification-catalog source spans.
CLI Help Documentation
docs/cli-reference.md
Update polylogue show help text from "matched conversation content (default streaming)" to "matched conversations (default full-content)".
Test Updates
tests/unit/cli/test_embed.py, tests/unit/core/test_config.py, tests/unit/ui/test_ui_visual.py
Switch embed tests to call public entrypoints; remove fts_enabled default assertion; relax renderer format-list test to allow additional formats.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Possibly related PRs

Suggested labels

type:fix, area:cli, area:storage, area:parser, area:schema, area:mcp, area:pipeline, area:docs, area:rendering

Poem

🐰 Forty fixes hop into place,
From parsers safe to schemas precise,
Plaintext renders without a trace,
Tags preserved through metadata ice,
Permissions chmod'd, typing unified—
The audit's bounty, audited and tried! 🌿

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 45.57% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'fix: aggregate small fixes from adversarial audit (waves 1+2)' accurately summarizes the main change: bundling 35 small-scope fixes discovered during adversarial audit.
Description check ✅ Passed The PR description follows the template structure with Summary, Problem, Solution, and Verification sections. It provides comprehensive details about the 35 fixes across multiple categories and includes verification command output.
Linked Issues check ✅ Passed All code changes align with requirements from linked issues #469, #467, #484, #473, and #488: parsers add str() guards on Role.normalize(), FTS triggers fixed to match schema and use rowid, metadata preserved with COALESCE, and 30+ other small fixes implemented.
Out of Scope Changes check ✅ Passed All changes are scoped to the linked issues and PR objectives. Changes include only the specified small fixes: parser guards, FTS DDL corrections, storage improvements, CLI enhancements, MCP refinements, security hardening, and typing updates—no extraneous modifications.

✏️ 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/fix/aggregate-small-fixes

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

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

Caution

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

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

460-484: ⚠️ Potential issue | 🟠 Major

max() will raise TypeError on mixed naive/aware rows, and a single malformed timestamp aborts the entire provenance build.

Two coupled defects in _parse_iso_timestamp and its callers:

  1. datetime.fromisoformat(value.replace("Z", "+00:00")) returns a naive datetime whenever the input string has no timezone offset (e.g., "2024-05-01T12:00:00" from a naive datetime's .isoformat()). When max() is called over a list mixing naive and aware datetimes, it raises TypeError: can't compare offset-naive and offset-aware datetimes. This is a realistic hazard: SessionProfile.updated_at is assigned from conversation.updated_at, which may be a naive datetime from certain sources; calling .isoformat() on it produces a naive string, which _parse_iso_timestamp parses back as naive.

  2. fromisoformat raises ValueError on any unparseable string. The new code has no try/except, so a single malformed timestamp (empty value, non-ISO format) crashes records_provenance for an entire day/week/rollup build.

Suggested hardening:

🛡️ Proposed fix
-def _parse_iso_timestamp(value: str) -> datetime:
-    """Parse an ISO 8601 timestamp string to a timezone-aware datetime."""
-    return datetime.fromisoformat(value.replace("Z", "+00:00"))
+def _parse_iso_timestamp(value: str) -> datetime | None:
+    """Parse an ISO 8601 timestamp string to a timezone-aware datetime.
+
+    Returns None for unparseable inputs. Naive results are coerced to UTC so
+    they can be compared against aware datetimes from other rows.
+    """
+    try:
+        parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
+    except ValueError:
+        return None
+    if parsed.tzinfo is None:
+        parsed = parsed.replace(tzinfo=timezone.utc)
+    return parsed
@@
-    materialized_at_values = [
-        _parse_iso_timestamp(str(getattr(row, materialized_at_attr)))
-        for row in row_list
-        if getattr(row, materialized_at_attr, None)
-    ]
-    materialized_at = max(materialized_at_values).isoformat() if materialized_at_values else "1970-01-01T00:00:00+00:00"
-    source_updated_at_values = [
-        _parse_iso_timestamp(str(getattr(row, source_updated_at_attr)))
-        for row in row_list
-        if getattr(row, source_updated_at_attr, None)
-    ]
-    source_updated_at = max(source_updated_at_values).isoformat() if source_updated_at_values else None
+    materialized_at_values = [
+        parsed
+        for row in row_list
+        if getattr(row, materialized_at_attr, None)
+        and (parsed := _parse_iso_timestamp(str(getattr(row, materialized_at_attr)))) is not None
+    ]
+    materialized_at = (
+        max(materialized_at_values).isoformat() if materialized_at_values else "1970-01-01T00:00:00+00:00"
+    )
+    source_updated_at_values = [
+        parsed
+        for row in row_list
+        if getattr(row, source_updated_at_attr, None)
+        and (parsed := _parse_iso_timestamp(str(getattr(row, source_updated_at_attr)))) is not None
+    ]
+    source_updated_at = max(source_updated_at_values).isoformat() if source_updated_at_values else None
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/archive_products.py` around lines 460 - 484, The provenance builder
currently crashes on mixed naive/aware timestamps and on any malformed
timestamp; update _parse_iso_timestamp to robustly parse ISO strings by: calling
datetime.fromisoformat(value.replace("Z", "+00:00")) inside a try/except
ValueError and returning None for unparseable inputs, and if the parsed datetime
has tzinfo is None, attach timezone.utc so it is offset-aware; then change
callers in records_provenance (the list comprehensions building
materialized_at_values and source_updated_at_values) to call
_parse_iso_timestamp and filter out None results before taking max so invalid or
missing timestamps are ignored and comparisons never mix naive and aware
datetimes.
polylogue/storage/backends/schema_ddl_product_profiles.py (1)

66-157: ⚠️ Potential issue | 🟠 Major

Make FTS rowid binding explicit in the INSERT triggers.

The DELETE/UPDATE triggers now key off rowid = old.rowid (the session_profiles rowid), which is correct. However, none of the INSERT triggers (session_profiles_fts_ai, session_profile_evidence_fts_ai, session_profile_inference_fts_ai, session_profile_enrichment_fts_ai, and the INSERT half of each _au trigger) explicitly bind the FTS rowid. They rely on the implicit invariant that auto-assigned session_profiles.rowid and auto-assigned *_fts.rowid stay in lockstep.

This assumption can break if:

  • FTS rows are bulk-inserted outside the trigger path before this trigger definition ships.
  • Pre-existing FTS rows were populated before the trigger existed (rowid alignment is not retroactively guaranteed).
  • Any future operation bulk-inserts into the FTS table.

For reference, the messages FTS triggers elsewhere in the codebase (schema_ddl_archive.py, fts_lifecycle.py) already use explicit rowid binding via SELECT:

INSERT INTO messages_fts(rowid, message_id, conversation_id, text)
SELECT new.rowid, new.message_id, new.conversation_id, new.text

Apply the same pattern to all four INSERT-side trigger blocks in session_profiles FTS tables. Also apply this fix to action_events_fts_ai and action_events_fts_au in schema_ddl_actions.py, which have the same gap. Additionally, ACTION_FTS_REBUILD_SQL in fts_lifecycle_sql.py lacks explicit rowid in its INSERT—align it with the pattern used by FTS_REBUILD_SQL (messages).

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

In `@polylogue/storage/backends/schema_ddl_product_profiles.py` around lines 66 -
157, The INSERT triggers for session_profiles FTS tables must explicitly set the
FTS rowid instead of relying on implicit alignment: change each INSERT in
session_profiles_fts_ai, session_profile_evidence_fts_ai,
session_profile_inference_fts_ai, session_profile_enrichment_fts_ai and the
INSERT portion of each *_fts_au to insert (rowid, conversation_id,
provider_name, text) via a SELECT new.rowid, new.conversation_id,
new.provider_name, new.<*_search_text> rather than VALUES(...); do the same fix
for action_events_fts_ai and action_events_fts_au in schema_ddl_actions.py, and
update ACTION_FTS_REBUILD_SQL in fts_lifecycle_sql.py to include rowid in its
INSERT (align with the messages FTS pattern that uses INSERT ... (rowid, ...)
SELECT new.rowid, ...).
polylogue/storage/backends/queries/conversations_writes.py (1)

49-78: ⚠️ Potential issue | 🟠 Major

Metadata-preservation COALESCE is a no-op in both upsert paths due to non-NULL bind values.

Both polylogue/storage/backends/queries/conversations_writes.py:49 and polylogue/pipeline/services/ingest_batch.py:171 use identical COALESCE logic to preserve existing metadata on conflict:

metadata = COALESCE(excluded.metadata, conversations.metadata)

However, in both paths the metadata bind parameter is never NULL:

  1. conversations_writes.py (line 73): _json_or_none(record.metadata) or "{}"—explicitly coerced to "{}".
  2. ingest_batch.py: Metadata comes from _conversation_tuple() (ingest_worker.py:706), which hardcodes it to "{}".

Since excluded.metadata is never NULL, COALESCE always selects the incoming "{}", overwriting any existing user tags on a content-hash change—exactly the regression the PR intended to fix.

To actually preserve existing metadata, remove the forced "{}" coercion:

  • conversations_writes.py: Drop or "{}" on line 73 so NULL is bound when no incoming metadata is provided.
  • ingest_batch.py: Modify _conversation_tuple() in ingest_worker.py line 706 to bind _json_or_none(conversation.metadata) instead of hardcoded "{}".

Ensure the INSERT side still produces a non-NULL row (e.g., via a column default '{}' if needed), or use the NULLIF pattern mentioned in the original analysis to differentiate between "no metadata supplied" and "user explicitly cleared tags".

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

In `@polylogue/storage/backends/queries/conversations_writes.py` around lines 49 -
78, The upsert is incorrectly forcing incoming metadata to a non-NULL "{}" so
COALESCE(excluded.metadata, conversations.metadata) is a no-op and overwrites
existing metadata; fix it by allowing a NULL bind when no metadata was supplied:
in the conversations upsert path remove the forced fallback (drop the `or "{}"`
after _json_or_none(record.metadata) so _json_or_none can return NULL), and in
the ingest path change the _conversation_tuple() call to bind
_json_or_none(conversation.metadata) instead of a hardcoded "{}", or
alternatively use NULLIF on the incoming parameter to map empty-string/"{}" to
NULL so the COALESCE preserves existing conversations.metadata when no metadata
was provided.
polylogue/readiness.py (1)

589-607: ⚠️ Potential issue | 🟠 Major

archive_root argument is ignored — function probes the wrong database for custom configs.

The signature accepts archive_root: Path, but the implementation calls the module-level db_path() (line 598), which always returns the default XDG-standard path (data_home() / "polylogue.db"). When a caller passes a custom config.archive_root (as helper_summary.py:121 does), the function silently probes the default database instead, returning misleading status.

Fix by honoring the caller's archive_root:

Proposed fix
-def quick_readiness_summary(archive_root: Path) -> str:
+def quick_readiness_summary(archive_root: Path | None = None) -> str:
     """Return a one-line readiness summary without running a full readiness pass.

     Reads basic DB stats (conversation count, schema version) for a cheap
     summary suitable for the non-verbose CLI status line.
     """
     try:
         from polylogue.storage.backends.schema import SCHEMA_VERSION

-        db_path_val = db_path()
+        db_path_val = (archive_root / "polylogue.db") if archive_root is not None else db_path()
         with _open_readiness_probe_connection(db_path_val) as conn:
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/readiness.py` around lines 589 - 607, quick_readiness_summary
currently ignores its archive_root parameter and always calls db_path(), so it
probes the default DB instead of the caller's archive; change the code to derive
the DB path from the provided archive_root (e.g., db_path_val = archive_root /
"polylogue.db") or, if db_path accepts an argument, call db_path(archive_root),
then pass that db_path_val into _open_readiness_probe_connection so
quick_readiness_summary honors the caller-supplied archive_root.
polylogue/storage/backends/schema_ddl_actions.py (1)

58-89: ⚠️ Potential issue | 🔴 Critical

Critical: action_events_fts DELETE/UPDATE triggers will silently fail due to rowid mismatch.

The AFTER INSERT trigger inserts into action_events_fts without specifying rowid, so FTS5 auto-assigns its own monotonically-increasing rowid independent of the source table. The AFTER DELETE and AFTER UPDATE triggers attempt to delete by WHERE rowid = old.rowid—but since the INSERT never locked the rowids together, these deletions silently fail, leaving stale FTS entries and corrupting the index on every update/delete.

Contrast with the working messages_fts pattern in polylogue/storage/backends/schema_ddl_archive.py, which explicitly passes new.rowid in INSERT/UPDATE to keep rowids in sync.

The same issue exists in four additional locations:

  • polylogue/storage/fts_lifecycle.py lines 117, 127
  • polylogue/storage/fts_lifecycle_sql.py lines 42, 88

All six INSERT statements must pass new.rowid (or for rebuild SQL, select the rowid from the source table).

Fix: pass `new.rowid` through to FTS
 CREATE TRIGGER IF NOT EXISTS action_events_fts_ai
 AFTER INSERT ON action_events BEGIN
-    INSERT INTO action_events_fts (event_id, message_id, conversation_id, action_kind, tool_name, text)
+    INSERT INTO action_events_fts (rowid, event_id, message_id, conversation_id, action_kind, tool_name, text)
     VALUES (
+        new.rowid,
         new.event_id,
         new.message_id,
         new.conversation_id,
         new.action_kind,
         new.normalized_tool_name,
         new.search_text
     );
 END;

 CREATE TRIGGER IF NOT EXISTS action_events_fts_au
 AFTER UPDATE ON action_events BEGIN
     DELETE FROM action_events_fts WHERE rowid = old.rowid;
-    INSERT INTO action_events_fts (event_id, message_id, conversation_id, action_kind, tool_name, text)
+    INSERT INTO action_events_fts (rowid, event_id, message_id, conversation_id, action_kind, tool_name, text)
     VALUES (
+        new.rowid,
         new.event_id,
         new.message_id,
         new.conversation_id,
         new.action_kind,
         new.normalized_tool_name,
         new.search_text
     );
 END;

Apply equivalent edits in fts_lifecycle.py and fts_lifecycle_sql.py rebuild statements.

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

In `@polylogue/storage/backends/schema_ddl_actions.py` around lines 58 - 89, The
FTS triggers insert into action_events_fts without setting the FTS rowid, so
later DELETE/UPDATE by WHERE rowid = old.rowid fails; update the CREATE TRIGGER
statements (action_events_fts_ai and action_events_fts_au) to explicitly include
the rowid column in the INSERT (e.g., INSERT INTO action_events_fts(rowid,
event_id, message_id, conversation_id, action_kind, tool_name, text) VALUES
(new.rowid, ...)) so the FTS rowids mirror the source table, and for any rebuild
SQL/selects in fts_lifecycle.py and fts_lifecycle_sql.py change their
INSERT/SELECT to pass the source rowid into the FTS table (or select rowid from
the source) so deletes/updates using old.rowid work correctly.
polylogue/pipeline/ids.py (1)

79-91: 🧹 Nitpick | 🔵 Trivial

Sentinel inconsistency between attachment_seed and _normalize_for_hash.

_normalize_for_hash uses _NULL_SENTINEL = "__POLYLOGUE_NULL__" for None, while line 81 uses the literal "<null>". The two helpers operate on different surfaces (seed vs. hash payload), but using the shared module-level sentinel here would prevent accidental collisions if a real attachment field ever literally contains the string <null> and would keep null-sentinel semantics in one place.

♻️ Proposed alignment
 def attachment_seed(provider_name: str, attachment: ParsedAttachment) -> str:
     return "|".join(
-        str(value) if value is not None else "<null>"
+        str(value) if value is not None else _NULL_SENTINEL
         for value in [

Note: this is itself a hash-input change, so apply only alongside the broader re-hash plan.

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

In `@polylogue/pipeline/ids.py` around lines 79 - 91, Replace the literal "<null>"
used in attachment_seed with the module-level sentinel constant (e.g.,
_NULL_SENTINEL) so attachment_seed and _normalize_for_hash use the same null
sentinel; update the generator in attachment_seed (function name:
attachment_seed) to emit _NULL_SENTINEL for None values instead of the
hard-coded string to keep null-sentinel semantics consistent with
_normalize_for_hash and avoid accidental collisions.
polylogue/mcp/server_mutation_tools.py (1)

53-77: ⚠️ Potential issue | 🟠 Major

Verify ID validation and document atomicity semantics.

Two issues confirmed in this refactor:

  1. No strict ID resolution. Unlike add_tag/remove_tag which are called on single IDs, bulk_tag_conversations does not call resolve_id(strict=True). The implementation silently skips unknown conversation IDs (line 160: continue if SELECT 1 returns no row). Passing a prefix or non-existent ID results in silent skip with no error; applied_count reflects only successfully tagged conversations and may confuse callers who expect rejection or error feedback for invalid IDs.

  2. Atomicity confirmed. The operation runs within a single transaction (async with backend.transaction()), so all tag updates either succeed together or fail together. However, the silent skipping of unknown IDs before the transaction means applied_count may not match the input conversation_ids list, which could be misleading if the endpoint does not clarify this behavior.

Recommend either: (a) call resolve_id(strict=True) on each ID upfront and return error for unknown IDs, matching the behavior of single-ID mutations, or (b) document that unknown/non-existent IDs are silently skipped and applied_count reflects only valid conversations updated.

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

In `@polylogue/mcp/server_mutation_tools.py` around lines 53 - 77,
bulk_tag_conversations currently silently skips unknown conversation IDs which
causes applied_count to be misleading; fix by resolving every ID strictly before
performing the bulk operation: in bulk_tag_conversations call
hooks.resolve_id(id, strict=True) (or the module's resolve_id(strict=True)
helper) for each conversation_id up front, collect any failures and immediately
return hooks.error_json listing invalid IDs if any are unresolved, and only then
call tag_store.bulk_add_tags(conversation_ids, tags); this ensures behavior
matches single-ID mutations (and keeps transaction atomicity) and makes
applied_count correspond to the provided IDs.
polylogue/storage/repository_writes.py (1)

124-139: ⚠️ Potential issue | 🟡 Minor

Minor: add_tag stores unstripped tag.

The non-empty guard uses tag.strip(), but the value appended to tags is the original tag. A whitespace-padded value like " foo" passes validation and is stored verbatim, which then fails to dedupe against an existing "foo" and causes order-dependent inconsistencies. Consider normalizing with tag = tag.strip() after validation (and applying the same normalization in bulk_add_tags).

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

In `@polylogue/storage/repository_writes.py` around lines 124 - 139, In add_tag
ensure you normalize the input before storing/deduping: after the initial
non-empty check, reassign tag = tag.strip() (and re-check length if needed) so
the value appended in the _add closure is the trimmed string; make the same
change in bulk_add_tags so each tag is stripped before validation/appending to
metadata and before deduplication, ensuring whitespace-padded variants (e.g., "
foo") are normalized to "foo" for consistent storage and dedupe behavior.
♻️ Duplicate comments (1)
polylogue/storage/fts_lifecycle.py (1)

114-130: ⚠️ Potential issue | 🔴 Critical

Same rowid mismatch as schema_ddl_actions.py — must be fixed here too.

This DDL is what restore_fts_triggers_async reinstalls after suspend_fts_triggers_async, so it has to mirror the source-of-truth schema. The INSERT in action_events_fts_ai and the re-INSERT in action_events_fts_au don't pass new.rowid, so FTS5 auto-assigns its own rowid — and the DELETE … WHERE rowid = old.rowid lines on 122 and 126 won't match the right row. After any bulk-ingest cycle (suspend → write → restore), updates and deletes against action_events will leave stale FTS rows behind.

Apply the same rowid-passing fix as in schema_ddl_actions.py, and also update ACTION_FTS_REBUILD_SQL in polylogue/storage/fts_lifecycle_sql.py so a rebuild preserves ae.rowid as the FTS rowid (otherwise the rebuild path produces FTS rowids that don't match action_events.rowid either).

🐛 Proposed fix
 _ACTION_FTS_TRIGGER_DDL = [
     """CREATE TRIGGER IF NOT EXISTS action_events_fts_ai
        AFTER INSERT ON action_events BEGIN
-           INSERT INTO action_events_fts(event_id, message_id, conversation_id, action_kind, tool_name, text)
-           VALUES (new.event_id, new.message_id, new.conversation_id, new.action_kind, new.normalized_tool_name, new.search_text);
+           INSERT INTO action_events_fts(rowid, event_id, message_id, conversation_id, action_kind, tool_name, text)
+           VALUES (new.rowid, new.event_id, new.message_id, new.conversation_id, new.action_kind, new.normalized_tool_name, new.search_text);
        END""",
     """CREATE TRIGGER IF NOT EXISTS action_events_fts_ad
        AFTER DELETE ON action_events BEGIN
            DELETE FROM action_events_fts WHERE rowid = old.rowid;
        END""",
     """CREATE TRIGGER IF NOT EXISTS action_events_fts_au
        AFTER UPDATE ON action_events BEGIN
            DELETE FROM action_events_fts WHERE rowid = old.rowid;
-           INSERT INTO action_events_fts(event_id, message_id, conversation_id, action_kind, tool_name, text)
-           VALUES (new.event_id, new.message_id, new.conversation_id, new.action_kind, new.normalized_tool_name, new.search_text);
+           INSERT INTO action_events_fts(rowid, event_id, message_id, conversation_id, action_kind, tool_name, text)
+           VALUES (new.rowid, new.event_id, new.message_id, new.conversation_id, new.action_kind, new.normalized_tool_name, new.search_text);
        END""",
 ]
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/storage/fts_lifecycle.py` around lines 114 - 130, The FTS trigger
INSERTs in ACTION_FTS_TRIGGER_DDL (triggers action_events_fts_ai and
action_events_fts_au) do not pass the source table rowid, causing FTS5 to assign
its own rowid and breaking subsequent DELETEs that use old.rowid; modify those
INSERT statements to supply new.rowid as the first value so FTS rowids mirror
action_events.rowid, and keep the DELETE in action_events_fts_ad as-is; also
update ACTION_FTS_REBUILD_SQL in polylogue/storage/fts_lifecycle_sql.py so the
rebuild INSERT preserves ae.rowid (use ae.rowid as the FTS rowid) to ensure
rebuilds produce matching rowids.
🤖 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/plans/topology-target.yaml`:
- Around line 150-153: The entry for polylogue/rendering/renderers/plaintext.py
is misplaced inside the polylogue/cli/commands alphabetical block and has an
incorrect loc value; move the entire mapping "path:
polylogue/rendering/renderers/plaintext.py / target:
polylogue/rendering/renderers/plaintext.py / owner: stable" out of the CLI
commands section and insert it into the rendering/renderers block immediately
after the markdown.py entry, and update loc from 20 to the correct 81 so the
file location and ordering are accurate.

In `@hatch_build.py`:
- Around line 60-63: The guard using POLYLOGUE_SDIST_BUILD in finalize (checking
self._generated_build_info and os.environ.get("POLYLOGUE_SDIST_BUILD")) is dead
because the env var is never exported; update the release/CI pipeline to export
POLYLOGUE_SDIST_BUILD=1 before running hatch build --target sdist so
_build_info_path.unlink(...) is skipped for sdist creation (allowing
_build_info.py to persist for downstream wheel builds), and ensure any scripts
invoking hatch for sdist include that export or equivalent environment
injection.

In `@polylogue/cli/commands/check.py`:
- Around line 112-120: The hidden alias doctor_command currently only copies
check_command.callback and check_command.params which loses
help/short_help/epilog/context_settings and reuses the same params list; update
the alias construction to copy all Click metadata from check_command (help,
short_help, epilog, context_settings, allow_extra_args, etc.) and create a
shallow copy of the params list instead of reusing the reference so changes to
one Command don't affect the other; locate doctor_command and replace the
current click.Command(...) call to pass these additional attributes (or clone
via check_command.copy() / recreate with explicit fields) while keeping
hidden=True and name="doctor".

In `@polylogue/cli/helper_summary.py`:
- Around line 138-146: The empty-archive hint is unreachable when the archive is
truly empty because both get_provider_conversation_counts and
get_provider_metrics_rows return empty lists and the current message block (the
if total_convs == 0: ... ui.console.print(...) code referencing inbox =
config.archive_root / "inbox") is nested inside an outer if counts: guard; move
that entire hint block out of that guard (or add an else: branch on the if
counts: check) so it prints whenever counts is empty or total_convs == 0,
ensuring the ui.console.print that references inbox and the "polylogue run all"
hint executes for first-run users.

In `@polylogue/cli/helper_support.py`:
- Around line 13-15: The fail(command: str, message: str) helper currently
ignores the command parameter causing existing call sites and tests (which
expect "command: message") to break; update fail to include the command in the
error text and raise Click's idiomatic exception instead of SystemExit:
construct a combined message like f"{command}: {message}" (or if command can be
empty, trim appropriately) and raise click.ClickException(combined_message) so
Click handles formatting and exit semantics; ensure references to the helper
(fail) keep the same signature so all ~30 call sites and tests remain valid.

In `@polylogue/cli/query_verbs.py`:
- Around line 76-102: The current heuristic in show_verb (mirroring open_verb)
treats any single token containing ":" as a conv_id and clears query terms,
which misroutes legitimate search terms; update show_verb to validate the token
before treating it as a conv_id by reusing the same stricter validation used for
open_verb (or implement a shared validator function) — e.g., accept only the
provider:id pattern with a finite set of providers and an id regexp (like hex or
base64) or require an explicit --id flag; change the logic around
_parent_query_terms + target_terms and the call to _execute_query_verb so it
only calls request.with_query_terms(()).with_param_updates(conv_id=...) when
validation passes, and add unit tests for show_verb covering valid conv_id
routing and rejected colon-containing search terms.

In `@polylogue/lib/pricing.py`:
- Around line 207-209: The loop in _normalize_model repeatedly calls
sorted(PRICING, key=len, reverse=True) on every invocation; precompute a
module-level constant (e.g., _PRICING_KEYS_BY_LENGTH = sorted(PRICING, key=len,
reverse=True)) and change the loop in _normalize_model to iterate over
_PRICING_KEYS_BY_LENGTH instead of calling sorted each time, keeping the same
logic and ensuring PRICING remains the source of truth.

In `@polylogue/mcp/server_mutation_tools.py`:
- Around line 60-63: Extract the hard-coded limits into module-level constants
and use them in the bulk validation: define constants like
_MAX_BULK_CONVERSATIONS = 100 and _MAX_BULK_TAGS = 20 at the top of the module,
replace the literal checks in bulk_tag_conversations that inspect
conversation_ids and tags with comparisons against those constants, and update
the error messages to reference the constant values (e.g., f"supports at most
{_MAX_BULK_CONVERSATIONS} conversation_ids") so the limits are documented in one
place and easy to synchronize with client/schema/docs.

In `@polylogue/pipeline/ids.py`:
- Around line 74-75: The change introduces NFC normalization in the string
normalizer and adds an attachment "digest" into the conversation_content_hash
payload (see the normalize("NFC") branch and the new digest field/_NULL_SENTINEL
usage), which will change all existing conversation_content_hash values and
break lookup/upsert logic; add a documented migration entry in
docs/plans/migrations.yaml (and/or CHANGELOG) that: describes the exact code
changes (normalize("NFC") in the string normalizer and inclusion of attachment
digest in conversation_content_hash computation), states whether this is an
intentional breaking change, and provides a mitigation plan (one of: a re-hash
migration script to recompute and update stored hashes using the new algorithm,
a backwards-compatibility step in conversation_exists_by_hash to accept old
hashes, or versioned hashing so old records remain discoverable). Ensure the
entry references conversation_content_hash, the normalizer function that uses
unicodedata.normalize("NFC"), the digest/_NULL_SENTINEL addition, and the
recommended migration path or rollback decision so consumers/tests are informed.

In `@polylogue/rendering/formatting.py`:
- Around line 142-146: The _csv_safe function currently checks only ("=", "+",
"-", "@") — update it to also treat tab, carriage return and newline as
dangerous by including "\t", "\r", and "\n" in the sentinel set (e.g., check if
value and value[0] in ("=", "+", "-", "@", "\t", "\r", "\n")) so those control
characters are prefixed with "'" as well; keep the existing return behavior and
function name (_csv_safe).

In `@polylogue/rendering/renderers/plaintext.py`:
- Around line 60-78: The _strip_markdown function is incomplete and fragile;
replace its hand-rolled regex approach in _strip_markdown with a production
markdown-to-plain-text renderer (e.g., use markdown-it-py with the mdit_plain
renderer or convert markdown→HTML then html2text) so fenced/indented code
blocks, lists, blockquotes, horizontal rules, reference-style links, autolinks,
and HTML tags are correctly rendered and asterisks in prose aren’t mangled;
update the function to call the chosen library’s plain-text render API, remove
the regex replacements, and add the library to requirements/imports so PlainText
output from _strip_markdown is robust.

In `@polylogue/storage/backends/async_sqlite.py`:
- Around line 329-332: Remove the per-connection os.chmod call in the async
context manager used by the connection factory (the block that yields conn in
async_sqlite.py) and instead perform a one-shot permission hardening in the
backend initialization path: add chmod logic to initialize_backend_state (or a
new helper it calls) to set 0o600 on the main DB file and, if present, its -wal
and -shm sidecar files; also remove the now-redundant chmod in
ensure_schema_once and ensure the _get_read_connection and the _read_pool
factory follow the same init-only policy so all open paths rely on the single
chmod-at-creation behavior and avoid extra syscalls on the hot path.

In `@polylogue/storage/blob_store.py`:
- Line 95: Remove the redundant os.chmod(tmp_path, 0o600) calls (three
occurrences) since tempfile.mkstemp() already creates temp files with mode 0o600
on POSIX; locate the occurrences where tmp_path is created via
tempfile.mkstemp() (the same scope using tmp_path) and delete those chmod lines
to clean up unnecessary defensive duplication.

In `@polylogue/storage/repository_writes.py`:
- Around line 141-178: bulk_add_tags currently accepts tags verbatim and can
persist invalid tags; replicate the same validation used by add_tag by
validating each tag in bulk_add_tags before opening the transaction: for each
tag ensure tag.strip() is non-empty and len(tag) <= 200 (or call the shared
validate function if one exists), and if any tag fails raise the same error
type/message that add_tag uses (or return a clear validation error) so invalid
tags are rejected up front; then proceed to use conversations_q.get_metadata and
conversations_q.update_metadata_raw as before.
- Around line 155-160: The existence check using await conn.execute(...) leaves
an aiosqlite.Cursor open (variable exists) and should be wrapped in an async
context manager to ensure closure; update the query to "SELECT 1 FROM
conversations WHERE conversation_id = ? LIMIT 1" and use "async with
conn.execute(... ) as cur:" (or equivalent) then call "await cur.fetchone()" to
decide whether to continue, ensuring the cursor is closed each iteration
(reference the conn.execute call and the exists variable/conversation_id in
repository_writes.py).

In `@tests/unit/cli/test_embed.py`:
- Around line 181-209: The test functions were renamed removing the required
underscore after the "test" prefix so pytest won't collect them; rename the
functions back to the pytest-compatible pattern (e.g., change
testembed_single_success → test_embed_single_success,
testembed_single_conversation_not_found →
test_embed_single_conversation_not_found, testembed_single_no_messages →
test_embed_single_no_messages, testembed_single_upsert_exception →
test_embed_single_upsert_exception and likewise restore underscores for any
testembed_batch_* or other testembed_* functions) so they match pytest's default
python_functions pattern `test_*`.

---

Outside diff comments:
In `@polylogue/archive_products.py`:
- Around line 460-484: The provenance builder currently crashes on mixed
naive/aware timestamps and on any malformed timestamp; update
_parse_iso_timestamp to robustly parse ISO strings by: calling
datetime.fromisoformat(value.replace("Z", "+00:00")) inside a try/except
ValueError and returning None for unparseable inputs, and if the parsed datetime
has tzinfo is None, attach timezone.utc so it is offset-aware; then change
callers in records_provenance (the list comprehensions building
materialized_at_values and source_updated_at_values) to call
_parse_iso_timestamp and filter out None results before taking max so invalid or
missing timestamps are ignored and comparisons never mix naive and aware
datetimes.

In `@polylogue/mcp/server_mutation_tools.py`:
- Around line 53-77: bulk_tag_conversations currently silently skips unknown
conversation IDs which causes applied_count to be misleading; fix by resolving
every ID strictly before performing the bulk operation: in
bulk_tag_conversations call hooks.resolve_id(id, strict=True) (or the module's
resolve_id(strict=True) helper) for each conversation_id up front, collect any
failures and immediately return hooks.error_json listing invalid IDs if any are
unresolved, and only then call tag_store.bulk_add_tags(conversation_ids, tags);
this ensures behavior matches single-ID mutations (and keeps transaction
atomicity) and makes applied_count correspond to the provided IDs.

In `@polylogue/pipeline/ids.py`:
- Around line 79-91: Replace the literal "<null>" used in attachment_seed with
the module-level sentinel constant (e.g., _NULL_SENTINEL) so attachment_seed and
_normalize_for_hash use the same null sentinel; update the generator in
attachment_seed (function name: attachment_seed) to emit _NULL_SENTINEL for None
values instead of the hard-coded string to keep null-sentinel semantics
consistent with _normalize_for_hash and avoid accidental collisions.

In `@polylogue/readiness.py`:
- Around line 589-607: quick_readiness_summary currently ignores its
archive_root parameter and always calls db_path(), so it probes the default DB
instead of the caller's archive; change the code to derive the DB path from the
provided archive_root (e.g., db_path_val = archive_root / "polylogue.db") or, if
db_path accepts an argument, call db_path(archive_root), then pass that
db_path_val into _open_readiness_probe_connection so quick_readiness_summary
honors the caller-supplied archive_root.

In `@polylogue/storage/backends/queries/conversations_writes.py`:
- Around line 49-78: The upsert is incorrectly forcing incoming metadata to a
non-NULL "{}" so COALESCE(excluded.metadata, conversations.metadata) is a no-op
and overwrites existing metadata; fix it by allowing a NULL bind when no
metadata was supplied: in the conversations upsert path remove the forced
fallback (drop the `or "{}"` after _json_or_none(record.metadata) so
_json_or_none can return NULL), and in the ingest path change the
_conversation_tuple() call to bind _json_or_none(conversation.metadata) instead
of a hardcoded "{}", or alternatively use NULLIF on the incoming parameter to
map empty-string/"{}" to NULL so the COALESCE preserves existing
conversations.metadata when no metadata was provided.

In `@polylogue/storage/backends/schema_ddl_actions.py`:
- Around line 58-89: The FTS triggers insert into action_events_fts without
setting the FTS rowid, so later DELETE/UPDATE by WHERE rowid = old.rowid fails;
update the CREATE TRIGGER statements (action_events_fts_ai and
action_events_fts_au) to explicitly include the rowid column in the INSERT
(e.g., INSERT INTO action_events_fts(rowid, event_id, message_id,
conversation_id, action_kind, tool_name, text) VALUES (new.rowid, ...)) so the
FTS rowids mirror the source table, and for any rebuild SQL/selects in
fts_lifecycle.py and fts_lifecycle_sql.py change their INSERT/SELECT to pass the
source rowid into the FTS table (or select rowid from the source) so
deletes/updates using old.rowid work correctly.

In `@polylogue/storage/backends/schema_ddl_product_profiles.py`:
- Around line 66-157: The INSERT triggers for session_profiles FTS tables must
explicitly set the FTS rowid instead of relying on implicit alignment: change
each INSERT in session_profiles_fts_ai, session_profile_evidence_fts_ai,
session_profile_inference_fts_ai, session_profile_enrichment_fts_ai and the
INSERT portion of each *_fts_au to insert (rowid, conversation_id,
provider_name, text) via a SELECT new.rowid, new.conversation_id,
new.provider_name, new.<*_search_text> rather than VALUES(...); do the same fix
for action_events_fts_ai and action_events_fts_au in schema_ddl_actions.py, and
update ACTION_FTS_REBUILD_SQL in fts_lifecycle_sql.py to include rowid in its
INSERT (align with the messages FTS pattern that uses INSERT ... (rowid, ...)
SELECT new.rowid, ...).

In `@polylogue/storage/repository_writes.py`:
- Around line 124-139: In add_tag ensure you normalize the input before
storing/deduping: after the initial non-empty check, reassign tag = tag.strip()
(and re-check length if needed) so the value appended in the _add closure is the
trimmed string; make the same change in bulk_add_tags so each tag is stripped
before validation/appending to metadata and before deduplication, ensuring
whitespace-padded variants (e.g., " foo") are normalized to "foo" for consistent
storage and dedupe behavior.

---

Duplicate comments:
In `@polylogue/storage/fts_lifecycle.py`:
- Around line 114-130: The FTS trigger INSERTs in ACTION_FTS_TRIGGER_DDL
(triggers action_events_fts_ai and action_events_fts_au) do not pass the source
table rowid, causing FTS5 to assign its own rowid and breaking subsequent
DELETEs that use old.rowid; modify those INSERT statements to supply new.rowid
as the first value so FTS rowids mirror action_events.rowid, and keep the DELETE
in action_events_fts_ad as-is; also update ACTION_FTS_REBUILD_SQL in
polylogue/storage/fts_lifecycle_sql.py so the rebuild INSERT preserves ae.rowid
(use ae.rowid as the FTS rowid) to ensure rebuilds produce matching rowids.
🪄 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: 714b76b9-45d6-403f-9124-a1ac5aa666e2

📥 Commits

Reviewing files that changed from the base of the PR and between 850c372 and 028cd58.

📒 Files selected for processing (68)
  • docs/cli-reference.md
  • docs/plans/topology-target.yaml
  • docs/test-quality-workflows.md
  • docs/verification-catalog.md
  • flake.nix
  • hatch_build.py
  • polylogue/archive_products.py
  • polylogue/artifacts.py
  • polylogue/cli/click_command_registration.py
  • polylogue/cli/commands/check.py
  • polylogue/cli/commands/embed.py
  • polylogue/cli/commands/export.py
  • polylogue/cli/helper_summary.py
  • polylogue/cli/helper_support.py
  • polylogue/cli/query_verbs.py
  • polylogue/config.py
  • polylogue/lib/embeddings/stats.py
  • polylogue/lib/pricing.py
  • polylogue/lib/session_payload_documents.py
  • polylogue/lib/timestamps.py
  • polylogue/logging.py
  • polylogue/mcp/payloads.py
  • polylogue/mcp/server_mutation_tools.py
  • polylogue/mcp/server_prompts.py
  • polylogue/mcp/server_support.py
  • polylogue/mcp/server_tools.py
  • polylogue/pipeline/ids.py
  • polylogue/pipeline/payload_types.py
  • polylogue/pipeline/run_finalization.py
  • polylogue/pipeline/semantic_capture.py
  • polylogue/pipeline/services/acquisition_records.py
  • polylogue/pipeline/services/indexing.py
  • polylogue/pipeline/services/ingest_batch.py
  • polylogue/pipeline/services/ingest_worker.py
  • polylogue/protocols.py
  • polylogue/readiness.py
  • polylogue/rendering/core_markdown.py
  • polylogue/rendering/formatting.py
  • polylogue/rendering/renderers/__init__.py
  • polylogue/rendering/renderers/plaintext.py
  • polylogue/schemas/privacy.py
  • polylogue/schemas/privacy_config.py
  • polylogue/site/publication_flow.py
  • polylogue/sources/assembly.py
  • polylogue/sources/drive_gateway.py
  • polylogue/sources/parsers/chatgpt.py
  • polylogue/sources/parsers/claude_common.py
  • polylogue/storage/backends/async_sqlite.py
  • polylogue/storage/backends/async_sqlite_archive.py
  • polylogue/storage/backends/connection.py
  • polylogue/storage/backends/queries/conversations_identity.py
  • polylogue/storage/backends/queries/conversations_writes.py
  • polylogue/storage/backends/queries/stats.py
  • polylogue/storage/backends/query_store_archive.py
  • polylogue/storage/backends/schema_ddl_actions.py
  • polylogue/storage/backends/schema_ddl_archive.py
  • polylogue/storage/backends/schema_ddl_product_profiles.py
  • polylogue/storage/blob_store.py
  • polylogue/storage/cursor_state.py
  • polylogue/storage/fts_lifecycle.py
  • polylogue/storage/query_models.py
  • polylogue/storage/repository_archive_conversations.py
  • polylogue/storage/repository_writes.py
  • polylogue/storage/run_state.py
  • polylogue/storage/session_product_runtime.py
  • polylogue/surface_payloads.py
  • tests/unit/cli/test_embed.py
  • tests/unit/core/test_config.py
💤 Files with no reviewable changes (4)
  • tests/unit/core/test_config.py
  • polylogue/config.py
  • polylogue/storage/backends/schema_ddl_archive.py
  • polylogue/cli/commands/embed.py

Comment on lines +150 to 153
- path: polylogue/rendering/renderers/plaintext.py
loc: 20
target: polylogue/rendering/renderers/plaintext.py
owner: stable

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
# Confirm the actual LOC of the new plaintext renderer and that no duplicate entry exists.
fd -t f 'plaintext.py' polylogue/rendering
fd -t f 'plaintext.py' polylogue/rendering --exec wc -l {}
echo "---"
rg -n 'plaintext\.py' docs/plans/topology-target.yaml

Repository: Sinity/polylogue

Length of output: 269


🏁 Script executed:

# Examine the YAML structure around the disputed entry (lines 140-160)
sed -n '140,160p' docs/plans/topology-target.yaml | cat -n

echo "---"

# Look for the rendering/renderers section to understand its boundaries
rg -n 'rendering.*renderers' docs/plans/topology-target.yaml | head -20

Repository: Sinity/polylogue

Length of output: 1717


🏁 Script executed:

# Check what comes after markdown.py in the rendering/renderers block
sed -n '1145,1160p' docs/plans/topology-target.yaml | cat -n

Repository: Sinity/polylogue

Length of output: 670


Misplaced entry: polylogue/rendering/renderers/plaintext.py inserted into the polylogue/cli/commands/ alphabetical block.

This entry sits between polylogue/cli/commands/dashboard.py (lines 146–149) and polylogue/cli/commands/export.py (line 154), breaking the alphabetical ordering of CLI commands and placing a rendering-renderer entry in the wrong section. It should be moved to the rendering/renderers block after markdown.py (around line 1145). The loc: 20 value is also incorrect; the actual file has 81 lines.

📐 Suggested move (within the rendering/renderers section)
@@ around lines 146-154 (CLI commands block) @@
   - path: polylogue/cli/commands/dashboard.py
     loc: 20
     target: polylogue/cli/commands/dashboard.py
     owner: stable
-  - path: polylogue/rendering/renderers/plaintext.py
-    loc: 20
-    target: polylogue/rendering/renderers/plaintext.py
-    owner: stable
   - path: polylogue/cli/commands/export.py
     loc: 34
     target: polylogue/cli/commands/export.py
     owner: stable
@@ around lines 1145-1148 (rendering/renderers block) @@
   - path: polylogue/rendering/renderers/markdown.py
     loc: 56
     target: polylogue/rendering/renderers/markdown.py
     owner: stable
+  - path: polylogue/rendering/renderers/plaintext.py
+    loc: 81
+    target: polylogue/rendering/renderers/plaintext.py
+    owner: stable
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs/plans/topology-target.yaml` around lines 150 - 153, The entry for
polylogue/rendering/renderers/plaintext.py is misplaced inside the
polylogue/cli/commands alphabetical block and has an incorrect loc value; move
the entire mapping "path: polylogue/rendering/renderers/plaintext.py / target:
polylogue/rendering/renderers/plaintext.py / owner: stable" out of the CLI
commands section and insert it into the rendering/renderers block immediately
after the markdown.py entry, and update loc from 20 to the correct 81 so the
file location and ordering are accurate.

Comment thread hatch_build.py Resolved
Comment thread polylogue/cli/commands/check.py Outdated
Comment on lines +112 to +120
# Hidden alias for backward compatibility
doctor_command = click.Command(
name="doctor",
hidden=True,
callback=check_command.callback,
params=check_command.params,
)

__all__ = ["check_command", "doctor_command"]

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major

Doctor alias drops --help text and other Click metadata.

The hidden alias only copies callback and params. check_command.help (derived from the docstring), short_help, epilog, context_settings, etc. are not propagated, so polylogue doctor --help will render without the description that polylogue check --help shows. Sharing the same params list reference between two Command instances is also slightly fragile.

♻️ Suggested fix
-# Hidden alias for backward compatibility
-doctor_command = click.Command(
-    name="doctor",
-    hidden=True,
-    callback=check_command.callback,
-    params=check_command.params,
-)
+# Hidden alias for backward compatibility
+doctor_command = click.Command(
+    name="doctor",
+    hidden=True,
+    callback=check_command.callback,
+    params=list(check_command.params),
+    help=check_command.help,
+    short_help=check_command.short_help,
+    epilog=check_command.epilog,
+    context_settings=check_command.context_settings,
+)
📝 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
# Hidden alias for backward compatibility
doctor_command = click.Command(
name="doctor",
hidden=True,
callback=check_command.callback,
params=check_command.params,
)
__all__ = ["check_command", "doctor_command"]
# Hidden alias for backward compatibility
doctor_command = click.Command(
name="doctor",
hidden=True,
callback=check_command.callback,
params=list(check_command.params),
help=check_command.help,
short_help=check_command.short_help,
epilog=check_command.epilog,
context_settings=check_command.context_settings,
)
__all__ = ["check_command", "doctor_command"]
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/cli/commands/check.py` around lines 112 - 120, The hidden alias
doctor_command currently only copies check_command.callback and
check_command.params which loses help/short_help/epilog/context_settings and
reuses the same params list; update the alias construction to copy all Click
metadata from check_command (help, short_help, epilog, context_settings,
allow_extra_args, etc.) and create a shallow copy of the params list instead of
reusing the reference so changes to one Command don't affect the other; locate
doctor_command and replace the current click.Command(...) call to pass these
additional attributes (or clone via check_command.copy() / recreate with
explicit fields) while keeping hidden=True and name="doctor".

Comment on lines +138 to +146
if total_convs == 0:
ui.console.print()
inbox = config.archive_root / "inbox"
ui.console.print(
"[yellow]No conversations yet. Drop export files in[/yellow] "
f"[bold]{inbox}[/bold]"
" [yellow]and run[/yellow] [bold]polylogue run all[/bold]"
)

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
# Confirm that get_provider_conversation_counts returns [] (not zero rows) for an empty archive,
# which would make the new branch unreachable in the empty-archive path.
rg -nP -C5 'def get_provider_conversation_counts\b'
rg -nP -C3 'get_provider_counts_fn|get_provider_conversation_counts' --type=py

Repository: Sinity/polylogue

Length of output: 8592


🏁 Script executed:

cat -n polylogue/storage/backends/queries/stats.py | sed -n '255,280p'

Repository: Sinity/polylogue

Length of output: 1084


🏁 Script executed:

cat -n polylogue/cli/helper_summary.py | sed -n '120,155p'

Repository: Sinity/polylogue

Length of output: 1729


🏁 Script executed:

rg -nP -C5 'def list_provider_analytics_products\b' polylogue/

Repository: Sinity/polylogue

Length of output: 4167


🏁 Script executed:

cat -n polylogue/storage/backends/queries/stats.py | sed -n '277,310p'

Repository: Sinity/polylogue

Length of output: 2558


🏁 Script executed:

cat -n polylogue/cli/helper_summary.py | sed -n '138,160p'

Repository: Sinity/polylogue

Length of output: 1147


Hoist the empty-archive message outside the if counts: guard.

This message is currently unreachable for a truly empty archive. Both code paths (get_provider_conversation_counts and get_provider_metrics_rows) return an empty list when the archive contains no conversations—they do not return rows with zero counts. When counts is empty, the outer if counts: guard evaluates to False, so the helpful "No conversations yet" hint never displays. A first-run user sees nothing after the summary panel.

Move this guidance to an else branch (or hoist it outside the guard entirely) so it prints whenever the archive is empty:

Proposed adjustment
-        if counts:
+        if not counts:
+            ui.console.print()
+            inbox = config.archive_root / "inbox"
+            ui.console.print(
+                "[yellow]No conversations yet. Drop export files in[/yellow] "
+                f"[bold]{inbox}[/bold]"
+                " [yellow]and run[/yellow] [bold]polylogue run all[/bold]"
+            )
+        else:
             ui.console.print()
             total_convs = sum(count for _, count in counts)
             ui.console.print(f"[bold]Archive:[/bold] {total_convs:,} conversations")
-
-            if total_convs == 0:
-                ui.console.print()
-                inbox = config.archive_root / "inbox"
-                ui.console.print(
-                    "[yellow]No conversations yet. Drop export files in[/yellow] "
-                    f"[bold]{inbox}[/bold]"
-                    " [yellow]and run[/yellow] [bold]polylogue run all[/bold]"
-                )
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/cli/helper_summary.py` around lines 138 - 146, The empty-archive
hint is unreachable when the archive is truly empty because both
get_provider_conversation_counts and get_provider_metrics_rows return empty
lists and the current message block (the if total_convs == 0: ...
ui.console.print(...) code referencing inbox = config.archive_root / "inbox") is
nested inside an outer if counts: guard; move that entire hint block out of that
guard (or add an else: branch on the if counts: check) so it prints whenever
counts is empty or total_convs == 0, ensuring the ui.console.print that
references inbox and the "polylogue run all" hint executes for first-run users.

Comment thread polylogue/cli/helper_support.py Outdated
Comment on lines +13 to +15
def fail(command: str, message: str) -> NoReturn:
raise SystemExit(f"{command}: {message}")
click.echo(f"Error: {message}", err=True)
raise SystemExit(1)

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

🏁 Script executed:

#!/bin/bash
# Confirm callers and check whether anyone relied on the old "command: message" format in tests.
rg -nP --type=py -C2 '\bfail\s*\(\s*["\']' 
rg -nP --type=py -C2 'from polylogue\.cli\.helper_support import .*\bfail\b'

Repository: Sinity/polylogue

Length of output: 129


🏁 Script executed:

#!/bin/bash
# First, check the actual implementation of fail() function
cat polylogue/cli/helper_support.py

Repository: Sinity/polylogue

Length of output: 547


🏁 Script executed:

#!/bin/bash
# Find all call sites of the fail() function
rg -n 'fail\s*\(' --type=py | head -20

Repository: Sinity/polylogue

Length of output: 2374


🏁 Script executed:

#!/bin/bash
# Search for imports of fail from helper_support
rg -n 'from.*helper_support.*import' --type=py

Repository: Sinity/polylogue

Length of output: 674


🏁 Script executed:

#!/bin/bash
# Look for any test files related to cli or helper_support
fd -type f -name '*test*.py' | grep -i cli

Repository: Sinity/polylogue

Length of output: 231


🏁 Script executed:

#!/bin/bash
# Find all actual calls to fail() function (not pytest.fail)
rg -n '\.fail\s*\(' --type=py -B2 -A2 | grep -v pytest | head -40

Repository: Sinity/polylogue

Length of output: 1476


🏁 Script executed:

#!/bin/bash
# Examine the test file that calls helpers.fail()
sed -n '40,55p' tests/unit/cli/test_source_selection_helpers.py

Repository: Sinity/polylogue

Length of output: 742


🏁 Script executed:

#!/bin/bash
# Search for all invocations of the fail function from helper_support
rg -n 'fail\s*\(\s*[^)]*\)' --type=py | grep -v pytest | grep -v 'def ' | grep -v '_fail'

Repository: Sinity/polylogue

Length of output: 4897


command parameter is now unused — either include it in the message or drop it.

The current implementation discards the command argument that all 30+ call sites still populate. The test expectations (parametrized with "test_cmd: something broke") confirm the previous behavior included command in the error message.

Pick one of the two fixes:

🛠️ Option A — restore operator context (preferred)
 def fail(command: str, message: str) -> NoReturn:
-    click.echo(f"Error: {message}", err=True)
+    click.echo(f"Error ({command}): {message}", err=True)
     raise SystemExit(1)
🛠️ Option B — drop the now-unused parameter and update all 30+ call sites
-def fail(command: str, message: str) -> NoReturn:
-    click.echo(f"Error: {message}", err=True)
+def fail(message: str) -> NoReturn:
+    click.echo(f"Error: {message}", err=True)
     raise SystemExit(1)

Also note that raise click.ClickException(message) is the idiomatic Click 8 approach — it integrates with Click's error handling, respects --no-color, and produces identical Error: {message}\n stderr output.

📝 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 fail(command: str, message: str) -> NoReturn:
raise SystemExit(f"{command}: {message}")
click.echo(f"Error: {message}", err=True)
raise SystemExit(1)
def fail(command: str, message: str) -> NoReturn:
click.echo(f"Error ({command}): {message}", err=True)
raise SystemExit(1)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/cli/helper_support.py` around lines 13 - 15, The fail(command: str,
message: str) helper currently ignores the command parameter causing existing
call sites and tests (which expect "command: message") to break; update fail to
include the command in the error text and raise Click's idiomatic exception
instead of SystemExit: construct a combined message like f"{command}: {message}"
(or if command can be empty, trim appropriately) and raise
click.ClickException(combined_message) so Click handles formatting and exit
semantics; ensure references to the helper (fail) keep the same signature so all
~30 call sites and tests remain valid.

Comment on lines 329 to 332
async with aiosqlite.connect(backend._db_path, timeout=DB_TIMEOUT) as conn:
os.chmod(backend._db_path, 0o600)
await configure_connection(conn)
yield conn

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Avoid chmod on the connection hot path; tighten WAL/SHM coverage.

os.chmod(backend._db_path, 0o600) here runs on every acquisition of a non-transaction, non-bulk, non-pool connection, adding a redundant syscall to the hot path — initialize_backend_state (line 104) and ensure_schema_once (line 128) already harden the file. There's also an inconsistency: _get_read_connection (line 362) and the _read_pool factory (lines 287–295) don't apply the same chmod, so the policy is partially enforced based on which path opens the file first.

Two suggestions:

  • Drop the per-connection chmod here (and remove the now-redundant one in ensure_schema_once); rely on the init-time hardening plus a single chmod immediately after the file is created on first connect.
  • Also chmod the *-wal / *-shm sidecars when they exist — they contain durable copies of DB pages and inherit default perms.
♻️ Sketch
-    async with aiosqlite.connect(backend._db_path, timeout=DB_TIMEOUT) as conn:
-        os.chmod(backend._db_path, 0o600)
-        await configure_connection(conn)
-        yield conn
+    async with aiosqlite.connect(backend._db_path, timeout=DB_TIMEOUT) as conn:
+        await configure_connection(conn)
+        yield conn

And in initialize_backend_state / a one-shot helper, harden the main DB plus its WAL/SHM sidecars together.

📝 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
async with aiosqlite.connect(backend._db_path, timeout=DB_TIMEOUT) as conn:
os.chmod(backend._db_path, 0o600)
await configure_connection(conn)
yield conn
async with aiosqlite.connect(backend._db_path, timeout=DB_TIMEOUT) as conn:
await configure_connection(conn)
yield conn
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/storage/backends/async_sqlite.py` around lines 329 - 332, Remove
the per-connection os.chmod call in the async context manager used by the
connection factory (the block that yields conn in async_sqlite.py) and instead
perform a one-shot permission hardening in the backend initialization path: add
chmod logic to initialize_backend_state (or a new helper it calls) to set 0o600
on the main DB file and, if present, its -wal and -shm sidecar files; also
remove the now-redundant chmod in ensure_schema_once and ensure the
_get_read_connection and the _read_pool factory follow the same init-only policy
so all open paths rely on the single chmod-at-creation behavior and avoid extra
syscalls on the hot path.

heartbeat()
os.close(fd)
fd = None
os.chmod(tmp_path, 0o600)

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

🧩 Analysis chain

🌐 Web query:

What file mode does Python's tempfile.mkstemp create files with on POSIX systems?

💡 Result:

On POSIX systems, Python’s tempfile.mkstemp creates the temporary file with permissions 0600 (read/write for the creating user only, no access for group/others).

Citations:


🏁 Script executed:

# Get the file size first to understand how to read it
wc -l polylogue/storage/blob_store.py

Repository: Sinity/polylogue

Length of output: 96


🏁 Script executed:

# Read around lines 95, 146, 176 to verify the context
echo "=== Around line 95 ===" && sed -n '85,105p' polylogue/storage/blob_store.py
echo "" && echo "=== Around line 146 ===" && sed -n '135,155p' polylogue/storage/blob_store.py
echo "" && echo "=== Around line 176 ===" && sed -n '165,185p' polylogue/storage/blob_store.py

Repository: Sinity/polylogue

Length of output: 2125


🏁 Script executed:

# Search for tempfile.mkstemp calls to confirm the pattern
rg -n 'tempfile\.mkstemp' polylogue/storage/blob_store.py

Repository: Sinity/polylogue

Length of output: 303


The three os.chmod(tmp_path, 0o600) calls are redundant — tempfile.mkstemp() already creates files with mode 0o600 on POSIX systems.

Since the temp file is created with the correct permissions by mkstemp(), the explicit chmod is unnecessary. The calls are harmless if kept as defensive coding, but can be safely removed.

Applies to lines 95, 146, and 176.

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

In `@polylogue/storage/blob_store.py` at line 95, Remove the redundant
os.chmod(tmp_path, 0o600) calls (three occurrences) since tempfile.mkstemp()
already creates temp files with mode 0o600 on POSIX; locate the occurrences
where tmp_path is created via tempfile.mkstemp() (the same scope using tmp_path)
and delete those chmod lines to clean up unnecessary defensive duplication.

Comment on lines +141 to +178
async def bulk_add_tags(self, conversation_ids: list[str], tags: list[str]) -> int:
"""Add tags to multiple conversations within a single transaction.

Args:
conversation_ids: List of conversation IDs to tag.
tags: List of tag strings to apply to each conversation.

Returns:
Number of conversations whose tags were actually changed.
"""
backend = self._backend
applied_count = 0
async with backend.transaction(), backend.connection() as conn:
for conversation_id in conversation_ids:
exists = await conn.execute(
"SELECT 1 FROM conversations WHERE conversation_id = ?",
(conversation_id,),
)
if not await exists.fetchone():
continue
current = await conversations_q.get_metadata(conn, conversation_id)
meta: JSONDocument = dict(current) if current else {}
existing_tags = list(string_sequence(meta.get("tags")))
changed = False
for tag in tags:
if tag not in existing_tags:
existing_tags.append(tag)
changed = True
if changed:
tag_payload: list[JSONValue] = list(existing_tags)
meta["tags"] = tag_payload
await conversations_q.update_metadata_raw(
conn,
conversation_id,
meta,
)
applied_count += 1
return applied_count

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

bulk_add_tags bypasses the new tag validation in add_tag.

add_tag now rejects empty/whitespace-only tags and tags longer than 200 characters, but bulk_add_tags accepts the tags list verbatim. The MCP bulk_tag_conversations tool is the primary caller and provides no equivalent validation, so a single bulk call can still persist invalid tags that the single-tag path forbids. Apply the same validation up front so behavior is consistent across surfaces.

🛡️ Suggested fix
 async def bulk_add_tags(self, conversation_ids: list[str], tags: list[str]) -> int:
     """Add tags to multiple conversations within a single transaction.
     ...
     """
+    for tag in tags:
+        if not tag or not tag.strip():
+            raise ValueError("tag must be a non-empty string")
+        if len(tag) > 200:
+            raise ValueError("tag must be at most 200 characters")
     backend = self._backend
     applied_count = 0
📝 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
async def bulk_add_tags(self, conversation_ids: list[str], tags: list[str]) -> int:
"""Add tags to multiple conversations within a single transaction.
Args:
conversation_ids: List of conversation IDs to tag.
tags: List of tag strings to apply to each conversation.
Returns:
Number of conversations whose tags were actually changed.
"""
backend = self._backend
applied_count = 0
async with backend.transaction(), backend.connection() as conn:
for conversation_id in conversation_ids:
exists = await conn.execute(
"SELECT 1 FROM conversations WHERE conversation_id = ?",
(conversation_id,),
)
if not await exists.fetchone():
continue
current = await conversations_q.get_metadata(conn, conversation_id)
meta: JSONDocument = dict(current) if current else {}
existing_tags = list(string_sequence(meta.get("tags")))
changed = False
for tag in tags:
if tag not in existing_tags:
existing_tags.append(tag)
changed = True
if changed:
tag_payload: list[JSONValue] = list(existing_tags)
meta["tags"] = tag_payload
await conversations_q.update_metadata_raw(
conn,
conversation_id,
meta,
)
applied_count += 1
return applied_count
async def bulk_add_tags(self, conversation_ids: list[str], tags: list[str]) -> int:
"""Add tags to multiple conversations within a single transaction.
Args:
conversation_ids: List of conversation IDs to tag.
tags: List of tag strings to apply to each conversation.
Returns:
Number of conversations whose tags were actually changed.
"""
for tag in tags:
if not tag or not tag.strip():
raise ValueError("tag must be a non-empty string")
if len(tag) > 200:
raise ValueError("tag must be at most 200 characters")
backend = self._backend
applied_count = 0
async with backend.transaction(), backend.connection() as conn:
for conversation_id in conversation_ids:
exists = await conn.execute(
"SELECT 1 FROM conversations WHERE conversation_id = ?",
(conversation_id,),
)
if not await exists.fetchone():
continue
current = await conversations_q.get_metadata(conn, conversation_id)
meta: JSONDocument = dict(current) if current else {}
existing_tags = list(string_sequence(meta.get("tags")))
changed = False
for tag in tags:
if tag not in existing_tags:
existing_tags.append(tag)
changed = True
if changed:
tag_payload: list[JSONValue] = list(existing_tags)
meta["tags"] = tag_payload
await conversations_q.update_metadata_raw(
conn,
conversation_id,
meta,
)
applied_count += 1
return applied_count
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/storage/repository_writes.py` around lines 141 - 178, bulk_add_tags
currently accepts tags verbatim and can persist invalid tags; replicate the same
validation used by add_tag by validating each tag in bulk_add_tags before
opening the transaction: for each tag ensure tag.strip() is non-empty and
len(tag) <= 200 (or call the shared validate function if one exists), and if any
tag fails raise the same error type/message that add_tag uses (or return a clear
validation error) so invalid tags are rejected up front; then proceed to use
conversations_q.get_metadata and conversations_q.update_metadata_raw as before.

Comment on lines +155 to +160
exists = await conn.execute(
"SELECT 1 FROM conversations WHERE conversation_id = ?",
(conversation_id,),
)
if not await exists.fetchone():
continue

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
# Confirm aiosqlite usage convention in this repo: cursors closed via async context manager.
rg -nP --type=py -C2 'await\s+conn\.execute\(' -g '!**/tests/**' | head -80

Repository: Sinity/polylogue

Length of output: 5764


🏁 Script executed:

cat -n polylogue/storage/repository_writes.py | sed -n '150,165p'

Repository: Sinity/polylogue

Length of output: 915


🏁 Script executed:

# Check the exact context around the flagged lines
head -170 polylogue/storage/repository_writes.py | tail -30

Repository: Sinity/polylogue

Length of output: 1438


🌐 Web query:

aiosqlite.Cursor lifecycle fetchone auto-close behavior

💡 Result:

The aiosqlite.Cursor does not auto-close when calling fetchone. Users must explicitly call await cursor.close after fetching all desired rows, or use a context manager (async with db.execute(...) as cursor: ...) which automatically closes the cursor upon exit. Official documentation shows Cursor has an explicit async close method and async fetchone method that fetches a single row and returns Row | None, with no mention of auto-closing on fetchone or end of results. Examples demonstrate manual close after fetchone/fetchall, or using context managers for auto-close. Like sqlite3.Cursor, closing is recommended for resource cleanup (resetting statements), though garbage collection may handle it. In aiosqlite's threaded model, explicit closing ensures proper queue handling. fetchone sends the request through the connection's thread queue to call sqlite3.Cursor.fetchone but does not close or reset the underlying cursor; it remains usable for further fetches until explicitly closed or connection closes.

Citations:


Close cursor after existence probe.

await conn.execute(...) returns an aiosqlite.Cursor that must be explicitly closed; calling fetchone() does not auto-close it. In this loop iterating up to 100 conversations, unclosed cursors accumulate until the transaction ends. Use an async context manager to ensure closure, and add LIMIT 1 for a minor efficiency improvement on existence checks.

♻️ Suggested fix
-            exists = await conn.execute(
-                "SELECT 1 FROM conversations WHERE conversation_id = ?",
-                (conversation_id,),
-            )
-            if not await exists.fetchone():
-                continue
+            async with conn.execute(
+                "SELECT 1 FROM conversations WHERE conversation_id = ? LIMIT 1",
+                (conversation_id,),
+            ) as exists:
+                if not await exists.fetchone():
+                    continue
📝 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
exists = await conn.execute(
"SELECT 1 FROM conversations WHERE conversation_id = ?",
(conversation_id,),
)
if not await exists.fetchone():
continue
async with conn.execute(
"SELECT 1 FROM conversations WHERE conversation_id = ? LIMIT 1",
(conversation_id,),
) as exists:
if not await exists.fetchone():
continue
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@polylogue/storage/repository_writes.py` around lines 155 - 160, The existence
check using await conn.execute(...) leaves an aiosqlite.Cursor open (variable
exists) and should be wrapped in an async context manager to ensure closure;
update the query to "SELECT 1 FROM conversations WHERE conversation_id = ? LIMIT
1" and use "async with conn.execute(... ) as cur:" (or equivalent) then call
"await cur.fetchone()" to decide whether to continue, ensuring the cursor is
closed each iteration (reference the conn.execute call and the exists
variable/conversation_id in repository_writes.py).

Comment on lines +181 to +209
def testembed_single_success(
self, mock_env: MagicMock, mock_repository_async: MagicMock, capsys: pytest.CaptureFixture[str]
) -> None:
mock_vec_provider = MagicMock()
_embed_single(mock_env, mock_repository_async, mock_vec_provider, "conv-123")
embed_single(mock_env, mock_repository_async, mock_vec_provider, "conv-123")
mock_vec_provider.upsert.assert_called_once_with("conv-123", mock_repository_async.get_messages.return_value)
captured = capsys.readouterr()
assert "Embedding 2 messages" in captured.out
assert "✓ Embedded" in captured.out

def test_embed_single_conversation_not_found(self, mock_env: MagicMock, mock_repository_async: MagicMock) -> None:
def testembed_single_conversation_not_found(self, mock_env: MagicMock, mock_repository_async: MagicMock) -> None:
mock_repository_async.view = AsyncMock(return_value=None)
with pytest.raises(click.Abort):
_embed_single(mock_env, mock_repository_async, MagicMock(), "nonexistent")
embed_single(mock_env, mock_repository_async, MagicMock(), "nonexistent")

def test_embed_single_no_messages(
def testembed_single_no_messages(
self, mock_env: MagicMock, mock_repository_async: MagicMock, capsys: pytest.CaptureFixture[str]
) -> None:
mock_repository_async.get_messages = AsyncMock(return_value=[])
mock_vec_provider = MagicMock()
_embed_single(mock_env, mock_repository_async, mock_vec_provider, "conv-123")
embed_single(mock_env, mock_repository_async, mock_vec_provider, "conv-123")
mock_vec_provider.upsert.assert_not_called()
assert "No messages to embed" in capsys.readouterr().out

def test_embed_single_upsert_exception(self, mock_env: MagicMock, mock_repository_async: MagicMock) -> None:
def testembed_single_upsert_exception(self, mock_env: MagicMock, mock_repository_async: MagicMock) -> None:
mock_vec_provider = MagicMock()
mock_vec_provider.upsert.side_effect = ValueError("API error")
with pytest.raises(click.Abort):
_embed_single(mock_env, mock_repository_async, mock_vec_provider, "conv-123")
embed_single(mock_env, mock_repository_async, mock_vec_provider, "conv-123")

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

🏁 Script executed:

#!/bin/bash
# Verify pytest config to confirm whether `testembed_*` methods will be collected.
fd -e toml -e ini -e cfg -H | xargs rg -nP --no-heading -C2 'python_functions|\[tool\.pytest|\[pytest\]' 2>/dev/null

echo "---"
# Confirm the rename pattern: methods starting with 'testembed' (no underscore) in this file.
rg -nP '^\s*def\s+testembed' tests/unit/cli/test_embed.py

Repository: Sinity/polylogue

Length of output: 807


Test methods will not be collected by pytest after the rename.

The rename from test_embed_single_* → testembed_single_* (and similarly for other test_embed_* methods) removes the underscore separator between the test prefix and the rest of the method name. Pytest's default python_functions pattern is test_*, which requires this underscore and will not match testembed_single_success, testembed_batch_variants, etc.

Since the repository's pyproject.toml does not define a custom python_functions configuration, all 8 affected test methods at lines 181, 191, 196, 205, 222, 248, 258, and 359 will be silently skipped during collection. No tests will run.

Restore the underscore: test_embed_single_*, test_embed_batch_*, etc.

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

In `@tests/unit/cli/test_embed.py` around lines 181 - 209, The test functions were
renamed removing the required underscore after the "test" prefix so pytest won't
collect them; rename the functions back to the pytest-compatible pattern (e.g.,
change testembed_single_success → test_embed_single_success,
testembed_single_conversation_not_found →
test_embed_single_conversation_not_found, testembed_single_no_messages →
test_embed_single_no_messages, testembed_single_upsert_exception →
test_embed_single_upsert_exception and likewise restore underscores for any
testembed_batch_* or other testembed_* functions) so they match pytest's default
python_functions pattern `test_*`.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 028cd58de8

ℹ️ 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 and others added 4 commits April 26, 2026 23:42
35 fixes across parsers, hashing, storage, CLI, MCP, rendering,
config, security, build, and dead code removal. Key changes:

- Parsers: str() guard on Role.normalize() inputs (fixes #469)
- Hashing: NFC normalization + attachment seed sentinel + digest in hash (fixes #472)
- Storage: FTS trigger DDL fix (#467), rowid triggers (#484), tags COALESCE (#473),
  readiness db_path fix, redundant index removal
- CLI: open_verb provider:id routing, show_verb, doctor→check, fail() unification,
  empty archive onboarding hint, export help text
- MCP: clamp_limit upper bound, get_stats_by Literal, resolve_id strict flag,
  bulk_tag_conversations size limits
- Rendering: heading escape all levels, CSV injection prevention
- Config: dead fts_enabled removal, max_length falsy fix, XDG dedup,
  POLYLOGUE_FORCE_PLAIN logging
- Security: db/blob chmod 0o600, manifest path leak fix
- Build: h2 Nix dep, hatch_build sdist fix, typing_extensions→stdlib typing
- Products: profile_bucket_day timezone, records_provenance ISO parsing,
  pricing.py model prefix ordering, name in privacy denylist
- Dead code: delete cli/commands/embed.py

Closes #488

Co-Authored-By: Claude Opus 4.7 <[email protected]>
- Revert doctor→check rename to avoid breaking scenario exercise IDs
  (json-doctor-* names are derived from the CLI command name)
- Remove duplicate doctor_command alias that created registration conflict
- Change fail() to use SystemExit(message) instead of SystemExit(1)
  so existing tests checking str(result.exception) continue working

Co-Authored-By: Claude Opus 4.7 <[email protected]>
- fail() SystemExit format with command: message prefix
- test_config.py fts_enabled removal
- test_list_formats len >= 2 for plaintext renderer
- Regenerate all generated docs

Co-Authored-By: Claude Opus 4.7 <[email protected]>
- Rebasing onto master introduced a duplicate show_verb definition
- ids.py digest arg type narrowed with explicit str() cast and .get() guard

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@Sinity
Sinity force-pushed the feature/fix/aggregate-small-fixes branch from ff0723c to ec13360 Compare April 26, 2026 22:23
@Sinity
Sinity merged commit 6b5c392 into master Apr 26, 2026
7 of 12 checks passed
@Sinity
Sinity deleted the feature/fix/aggregate-small-fixes branch April 26, 2026 22:24
Sinity added a commit that referenced this pull request Apr 27, 2026
#505)

## Summary

Master CI has been red since 6b5c392 (#489) due to 14 unrelated test
failures. This PR fixes them all in one mechanical pass so the
architecture-series PRs (#502 and follow-ups) can land.

## Problem

Failures span four root causes:

1. **Python 3.11 / pydantic TypedDict.** Pydantic 2.12+ refuses
`typing.TypedDict` on Python < 3.12. 19 modules declare TypedDict
subclasses; they all need to import from `typing_extensions`.
2. **MCP mutation tests don't mock the new resolve_id pre-check.**
Mutation tools resolve the conversation_id via the query store before
mutating; tests only patched `_get_tag_store`, so resolve_id returned
None and the tools short-circuited with "conversation not found".
3. **Schema/contract drift.** `_clamp_limit` caps at 1000 but tests
still echo unbounded inputs. `get_stats_by` gained an enum on `group_by`
but the witness wasn't regenerated. `bulk_tag_conversations` switched to
`bulk_add_tags(ids, tags)` but the test still asserts N×M `add_tag`
awaits.
4. **Env-sensitive logging test.** `configure_logging` honors
`POLYLOGUE_FORCE_PLAIN`; CI sets that env to `1`, so
`ConsoleRenderer(colors=True)` is unreachable from inside CI.

## Solution

Six targeted fixes:

1. Switch 19 files from `typing.TypedDict` to
`typing_extensions.TypedDict`. Add `typing-extensions>=4.7` to
`pyproject.toml` (works on all supported Pythons).
2. Add `resolved_id` parameter to `make_query_store_mock` and patch
`_get_query_store` in affected mutation tests (`add_tag`, `remove_tag`,
`set_metadata`, `delete_metadata`, `delete_conversation`).
3. Update `_clamp_limit` parametrized cases (5000/10001/99999 → 1000);
regen `tests/data/witnesses/mcp-tool-schemas.json`; rewrite bulk_tag
test to assert on `bulk_add_tags`.
4. Add `patch.dict("os.environ")` + `env.pop("POLYLOGUE_FORCE_PLAIN")`
to the logging test.
5. Refresh syrupy `test_terminal_snapshots.ambr` (same drift as #503;
included here to make the unit suite green standalone).

## Verification

```
POLYLOGUE_FORCE_PLAIN=1 pytest tests/unit/mcp/ \
  tests/unit/test_logging_runtime.py \
  tests/unit/cli/test_terminal_snapshots.py --no-cov
→ all pass

devtools verify --quick
→ all checks passed (pre-push hook)
```

## Out of scope

`test_cli_tail_list_json_exposes_tail_provenance` is failing on a TOCTOU
warning from a parallel BlobStore fix (in `feature/fix/audit-final` /
d295503). Tracked there; not in this PR.

## Related

- #503 — baseline + syrupy refresh; this PR includes the syrupy bit
again so master test suite is green even without #503.
- #502 — topology projection cleanup; blocked on master CI being green.
- #489 — the merge that introduced the 14 failures (test code wasn't
updated alongside MCP authz/limits + clamp_limit + bulk_add_tags + the
show/export help text changes that landed across several merges).


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Documentation**
* Enhanced CLI help text for export and show commands with clearer
descriptions of conversation ID format handling and default output
behavior.
* Reordered MCP tool schema parameters with added validation
constraints.

* **Chores**
  * Added `typing-extensions>=4.7` as a runtime dependency.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Sinity added a commit that referenced this pull request Apr 27, 2026
… site (#504)

## Summary

Six fixes from the adversarial audit that remained after #489, plus a
CodeQL-flagged refinement of the new HTML sanitizer.

## Problem

The audit pass after #489 surfaced six concrete bugs across hashing,
storage durability, lifecycle hygiene, parser ordering, site rendering,
and template safety:

- **Content-block coverage in content hash (#466)**: tool-use /
tool-result / thinking blocks were excluded from
`message_content_hash()` and `conversation_content_hash()`, producing
silent identity collisions on re-import for any conversation that has
structured content blocks.
- **BlobStore TOCTOU race (#470)**: `write_from_path()` read the source
file twice (once to hash, once to copy). Source mutations between the
two reads landed inconsistent (hash, content) pairs in the blob store.
- **Connection cache leak on exit (#473)**: cached SQLite connections
were not closed on process exit; ResourceWarnings and occasional WAL
leftovers in tests.
- **Provider detection ordering (#477)**: `codex.looks_like` and
`claude.looks_like_code` ran *after* the weaker dict-key heuristics, so
codex/claude-code records that also matched a generic shape were
misclassified.
- **Template XSS surface (#468)**: conversation templates used `{{
msg.html_content | safe }}`; any pre-rendered HTML reached the page
unfiltered. Defense-in-depth in the template layer was missing.
- **Site dropping content_block-only messages (#475)**: the per-message
render guard was `if not msg.text`, so messages whose payload lives
entirely in content_blocks (e.g. tool_use without summary text) silently
disappeared from generated sites.

After the original PR opened, CodeQL further flagged the new sanitizer's
`</script>` literal as not matching `</script >` (whitespace before
`>`), which browsers accept — a regex bypass.

## Solution

One commit per concern, plus the sanitizer regression follow-up:

- `pipeline/ids.py` — added `_content_block_payload()`;
`message_content_hash()` and `conversation_content_hash()` now include
normalized content blocks. Closes #466.
- `storage/blob_store.py` — rewrote `write_from_path()` to hash and
write to a temp file in a single pass, then rename atomically. Closes
#470.
- `storage/backends/connection.py` — registered `atexit` handler closing
every cached connection. Closes #473.
- `sources/dispatch.py` — moved `codex.looks_like` and
`claude.looks_like_code` ahead of the dict-key shape checks. Closes
#477.
- `rendering/renderers/html_sanitizer.py` (new) + `html_template.py` +
`templates/conversation.html` + `site/templates_conversation.py` +
`site/template_environment.py` + `site/search.py` — Jinja2
`sanitize_html` filter strips `<script>` tags, `on*` event handlers, and
`javascript:` URLs. All conversation templates use `| sanitize_html`
instead of `| safe`. Client-side search escapes user data before
`innerHTML`. Closes #468.
- `site/conversation_pages.py` — render guard now respects
`msg.content_blocks` (renders when text *or* blocks are present). Closes
#475.
- `rendering/renderers/html_sanitizer.py` (sanitizer fix-up commit) —
closing-tag regex now accepts `</script\s*>` rather than only
`</script>`. New `tests/unit/rendering/test_html_sanitizer.py` covers
whitespace-before-`>`, mixed case, attributed opening tags, multiline
bodies, event handlers, javascript URLs, safe markup, and empty input.

## Verification

```
devtools verify
  ruff format / check ... ok
  mypy ... ok (642 source files)
  render-all ... ok
  verify-topology / -file-budgets / -test-ownership / -migrations / -cross-cuts ... ok
  pytest -q --ignore=tests/integration ... 5751 passed (incl. new sanitizer tests)
verify: all checks passed
```

CodeQL annotation on the sanitizer regex is addressed by the second
commit (closing-tag whitespace tolerance + regression suite).

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

## Release Notes

* **Security Enhancements**
  * HTML content is now sanitized to prevent script injection attacks
* Search results are escaped to protect against malicious content
injection

* **New Features**
  * Enhanced message rendering with improved content support

* **Performance & Stability**
  * Optimized blob storage operations for faster writes
  * Improved database connection cleanup on exit
  * Provider detection refinements

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 4.7 <[email protected]>
@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. 5 finding(s) confirmed still present → tracked in #550.

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.

Copilot encountered an error and was unable to review this pull request. You can try again by re-requesting a review.

Sinity added a commit that referenced this pull request May 7, 2026
35 fixes across parsers, hashing, storage, CLI, MCP, rendering, config, security, build, and dead code removal. Discovered during 27-agent adversarial audit.

- Parsers: str() guard on Role.normalize() inputs 
- Hashing: NFC normalization + attachment seed sentinel + digest in hash
- Storage: FTS trigger DDL fix, rowid triggers, tags COALESCE, readiness db_path fix, redundant index
- CLI: open_verb provider:id routing, show_verb, fail() unified, onboarding hint, export help
- MCP: clamp_limit upper bound, get_stats_by Literal, resolve_id strict, bulk_tag limits
- Rendering: heading escape all levels, CSV injection prevention, plaintext renderer
- Config: dead fts_enabled removal, max_length falsy fix, XDG dedup, POLYLOGUE_FORCE_PLAIN logging
- Security: db/blob chmod 0o600, manifest path leak fix
- Build: h2 Nix dep, hatch_build sdist fix, typing_extensions→stdlib typing
- Products: profile_bucket_day timezone, records_provenance ISO parsing, pricing prefix ordering
- Dead code: delete cli/commands/embed.py

Closes #488

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Sinity added a commit that referenced this pull request May 7, 2026
#505)

## Summary

Master CI has been red since ddf212f (#489) due to 14 unrelated test
failures. This PR fixes them all in one mechanical pass so the
architecture-series PRs (#502 and follow-ups) can land.

## Problem

Failures span four root causes:

1. **Python 3.11 / pydantic TypedDict.** Pydantic 2.12+ refuses
`typing.TypedDict` on Python < 3.12. 19 modules declare TypedDict
subclasses; they all need to import from `typing_extensions`.
2. **MCP mutation tests don't mock the new resolve_id pre-check.**
Mutation tools resolve the conversation_id via the query store before
mutating; tests only patched `_get_tag_store`, so resolve_id returned
None and the tools short-circuited with "conversation not found".
3. **Schema/contract drift.** `_clamp_limit` caps at 1000 but tests
still echo unbounded inputs. `get_stats_by` gained an enum on `group_by`
but the witness wasn't regenerated. `bulk_tag_conversations` switched to
`bulk_add_tags(ids, tags)` but the test still asserts N×M `add_tag`
awaits.
4. **Env-sensitive logging test.** `configure_logging` honors
`POLYLOGUE_FORCE_PLAIN`; CI sets that env to `1`, so
`ConsoleRenderer(colors=True)` is unreachable from inside CI.

## Solution

Six targeted fixes:

1. Switch 19 files from `typing.TypedDict` to
`typing_extensions.TypedDict`. Add `typing-extensions>=4.7` to
`pyproject.toml` (works on all supported Pythons).
2. Add `resolved_id` parameter to `make_query_store_mock` and patch
`_get_query_store` in affected mutation tests (`add_tag`, `remove_tag`,
`set_metadata`, `delete_metadata`, `delete_conversation`).
3. Update `_clamp_limit` parametrized cases (5000/10001/99999 → 1000);
regen `tests/data/witnesses/mcp-tool-schemas.json`; rewrite bulk_tag
test to assert on `bulk_add_tags`.
4. Add `patch.dict("os.environ")` + `env.pop("POLYLOGUE_FORCE_PLAIN")`
to the logging test.
5. Refresh syrupy `test_terminal_snapshots.ambr` (same drift as #503;
included here to make the unit suite green standalone).

## Verification

```
POLYLOGUE_FORCE_PLAIN=1 pytest tests/unit/mcp/ \
  tests/unit/test_logging_runtime.py \
  tests/unit/cli/test_terminal_snapshots.py --no-cov
→ all pass

devtools verify --quick
→ all checks passed (pre-push hook)
```

## Out of scope

`test_cli_tail_list_json_exposes_tail_provenance` is failing on a TOCTOU
warning from a parallel BlobStore fix (in `feature/fix/audit-final` /
d295503). Tracked there; not in this PR.

## Related

- #503 — baseline + syrupy refresh; this PR includes the syrupy bit
again so master test suite is green even without #503.
- #502 — topology projection cleanup; blocked on master CI being green.
- #489 — the merge that introduced the 14 failures (test code wasn't
updated alongside MCP authz/limits + clamp_limit + bulk_add_tags + the
show/export help text changes that landed across several merges).


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Documentation**
* Enhanced CLI help text for export and show commands with clearer
descriptions of conversation ID format handling and default output
behavior.
* Reordered MCP tool schema parameters with added validation
constraints.

* **Chores**
  * Added `typing-extensions>=4.7` as a runtime dependency.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Sinity added a commit that referenced this pull request May 7, 2026
… site (#504)

## Summary

Six fixes from the adversarial audit that remained after #489, plus a
CodeQL-flagged refinement of the new HTML sanitizer.

## Problem

The audit pass after #489 surfaced six concrete bugs across hashing,
storage durability, lifecycle hygiene, parser ordering, site rendering,
and template safety:

- **Content-block coverage in content hash (#466)**: tool-use /
tool-result / thinking blocks were excluded from
`message_content_hash()` and `conversation_content_hash()`, producing
silent identity collisions on re-import for any conversation that has
structured content blocks.
- **BlobStore TOCTOU race (#470)**: `write_from_path()` read the source
file twice (once to hash, once to copy). Source mutations between the
two reads landed inconsistent (hash, content) pairs in the blob store.
- **Connection cache leak on exit (#473)**: cached SQLite connections
were not closed on process exit; ResourceWarnings and occasional WAL
leftovers in tests.
- **Provider detection ordering (#477)**: `codex.looks_like` and
`claude.looks_like_code` ran *after* the weaker dict-key heuristics, so
codex/claude-code records that also matched a generic shape were
misclassified.
- **Template XSS surface (#468)**: conversation templates used `{{
msg.html_content | safe }}`; any pre-rendered HTML reached the page
unfiltered. Defense-in-depth in the template layer was missing.
- **Site dropping content_block-only messages (#475)**: the per-message
render guard was `if not msg.text`, so messages whose payload lives
entirely in content_blocks (e.g. tool_use without summary text) silently
disappeared from generated sites.

After the original PR opened, CodeQL further flagged the new sanitizer's
`</script>` literal as not matching `</script >` (whitespace before
`>`), which browsers accept — a regex bypass.

## Solution

One commit per concern, plus the sanitizer regression follow-up:

- `pipeline/ids.py` — added `_content_block_payload()`;
`message_content_hash()` and `conversation_content_hash()` now include
normalized content blocks. Closes #466.
- `storage/blob_store.py` — rewrote `write_from_path()` to hash and
write to a temp file in a single pass, then rename atomically. Closes
#470.
- `storage/backends/connection.py` — registered `atexit` handler closing
every cached connection. Closes #473.
- `sources/dispatch.py` — moved `codex.looks_like` and
`claude.looks_like_code` ahead of the dict-key shape checks. Closes
#477.
- `rendering/renderers/html_sanitizer.py` (new) + `html_template.py` +
`templates/conversation.html` + `site/templates_conversation.py` +
`site/template_environment.py` + `site/search.py` — Jinja2
`sanitize_html` filter strips `<script>` tags, `on*` event handlers, and
`javascript:` URLs. All conversation templates use `| sanitize_html`
instead of `| safe`. Client-side search escapes user data before
`innerHTML`. Closes #468.
- `site/conversation_pages.py` — render guard now respects
`msg.content_blocks` (renders when text *or* blocks are present). Closes
#475.
- `rendering/renderers/html_sanitizer.py` (sanitizer fix-up commit) —
closing-tag regex now accepts `</script\s*>` rather than only
`</script>`. New `tests/unit/rendering/test_html_sanitizer.py` covers
whitespace-before-`>`, mixed case, attributed opening tags, multiline
bodies, event handlers, javascript URLs, safe markup, and empty input.

## Verification

```
devtools verify
  ruff format / check ... ok
  mypy ... ok (642 source files)
  render-all ... ok
  verify-topology / -file-budgets / -test-ownership / -migrations / -cross-cuts ... ok
  pytest -q --ignore=tests/integration ... 5751 passed (incl. new sanitizer tests)
verify: all checks passed
```

CodeQL annotation on the sanitizer regex is addressed by the second
commit (closing-tag whitespace tolerance + regression suite).

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

## Release Notes

* **Security Enhancements**
  * HTML content is now sanitized to prevent script injection attacks
* Search results are escaped to protect against malicious content
injection

* **New Features**
  * Enhanced message rendering with improved content support

* **Performance & Stability**
  * Optimized blob storage operations for faster writes
  * Improved database connection cleanup on exit
  * Provider detection refinements

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

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

None yet

Projects

None yet

2 participants