Repository navigation
fix: aggregate small fixes from adversarial audit (waves 1+2) - #489
Conversation
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (66)
📝 WalkthroughWalkthroughApplies ~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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~75 minutes Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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 raiseTypeErroron mixed naive/aware rows, and a single malformed timestamp aborts the entire provenance build.Two coupled defects in
_parse_iso_timestampand its callers:
datetime.fromisoformat(value.replace("Z", "+00:00"))returns a naivedatetimewhenever the input string has no timezone offset (e.g.,"2024-05-01T12:00:00"from a naive datetime's.isoformat()). Whenmax()is called over a list mixing naive and aware datetimes, it raisesTypeError: can't compare offset-naive and offset-aware datetimes. This is a realistic hazard:SessionProfile.updated_atis assigned fromconversation.updated_at, which may be a naive datetime from certain sources; calling.isoformat()on it produces a naive string, which_parse_iso_timestampparses back as naive.
fromisoformatraisesValueErroron any unparseable string. The new code has notry/except, so a single malformed timestamp (empty value, non-ISO format) crashesrecords_provenancefor 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 | 🟠 MajorMake FTS rowid binding explicit in the INSERT triggers.
The DELETE/UPDATE triggers now key off
rowid = old.rowid(thesession_profilesrowid), 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_autrigger) explicitly bind the FTS rowid. They rely on the implicit invariant that auto-assignedsession_profiles.rowidand auto-assigned*_fts.rowidstay 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.textApply the same pattern to all four INSERT-side trigger blocks in session_profiles FTS tables. Also apply this fix to
action_events_fts_aiandaction_events_fts_auin 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 | 🟠 MajorMetadata-preservation COALESCE is a no-op in both upsert paths due to non-NULL bind values.
Both
polylogue/storage/backends/queries/conversations_writes.py:49andpolylogue/pipeline/services/ingest_batch.py:171use 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:
- conversations_writes.py (line 73):
_json_or_none(record.metadata) or "{}"—explicitly coerced to"{}".- ingest_batch.py: Metadata comes from
_conversation_tuple()(ingest_worker.py:706), which hardcodes it to"{}".Since
excluded.metadatais 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_rootargument is ignored — function probes the wrong database for custom configs.The signature accepts
archive_root: Path, but the implementation calls the module-leveldb_path()(line 598), which always returns the default XDG-standard path (data_home() / "polylogue.db"). When a caller passes a customconfig.archive_root(ashelper_summary.py:121does), 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 | 🔴 CriticalCritical:
action_events_ftsDELETE/UPDATE triggers will silently fail due to rowid mismatch.The
AFTER INSERTtrigger inserts intoaction_events_ftswithout specifyingrowid, so FTS5 auto-assigns its own monotonically-increasing rowid independent of the source table. TheAFTER DELETEandAFTER UPDATEtriggers attempt to delete byWHERE 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_ftspattern inpolylogue/storage/backends/schema_ddl_archive.py, which explicitly passesnew.rowidin INSERT/UPDATE to keep rowids in sync.The same issue exists in four additional locations:
polylogue/storage/fts_lifecycle.pylines 117, 127polylogue/storage/fts_lifecycle_sql.pylines 42, 88All 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.pyandfts_lifecycle_sql.pyrebuild 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 | 🔵 TrivialSentinel inconsistency between
attachment_seedand_normalize_for_hash.
_normalize_for_hashuses_NULL_SENTINEL = "__POLYLOGUE_NULL__"forNone, 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 | 🟠 MajorVerify ID validation and document atomicity semantics.
Two issues confirmed in this refactor:
No strict ID resolution. Unlike
add_tag/remove_tagwhich are called on single IDs,bulk_tag_conversationsdoes not callresolve_id(strict=True). The implementation silently skips unknown conversation IDs (line 160:continueifSELECT 1returns no row). Passing a prefix or non-existent ID results in silent skip with no error;applied_countreflects only successfully tagged conversations and may confuse callers who expect rejection or error feedback for invalid IDs.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 meansapplied_countmay not match the inputconversation_idslist, 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 andapplied_countreflects 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 | 🟡 MinorMinor:
add_tagstores unstripped tag.The non-empty guard uses
tag.strip(), but the value appended totagsis the originaltag. 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 withtag = tag.strip()after validation (and applying the same normalization inbulk_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 | 🔴 CriticalSame rowid mismatch as
schema_ddl_actions.py— must be fixed here too.This DDL is what
restore_fts_triggers_asyncreinstalls aftersuspend_fts_triggers_async, so it has to mirror the source-of-truth schema. The INSERT inaction_events_fts_aiand the re-INSERT inaction_events_fts_audon't passnew.rowid, so FTS5 auto-assigns its own rowid — and theDELETE … WHERE rowid = old.rowidlines on 122 and 126 won't match the right row. After any bulk-ingest cycle (suspend → write → restore), updates and deletes againstaction_eventswill leave stale FTS rows behind.Apply the same
rowid-passing fix as inschema_ddl_actions.py, and also updateACTION_FTS_REBUILD_SQLinpolylogue/storage/fts_lifecycle_sql.pyso a rebuild preservesae.rowidas the FTS rowid (otherwise the rebuild path produces FTS rowids that don't matchaction_events.rowideither).🐛 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
📒 Files selected for processing (68)
docs/cli-reference.mddocs/plans/topology-target.yamldocs/test-quality-workflows.mddocs/verification-catalog.mdflake.nixhatch_build.pypolylogue/archive_products.pypolylogue/artifacts.pypolylogue/cli/click_command_registration.pypolylogue/cli/commands/check.pypolylogue/cli/commands/embed.pypolylogue/cli/commands/export.pypolylogue/cli/helper_summary.pypolylogue/cli/helper_support.pypolylogue/cli/query_verbs.pypolylogue/config.pypolylogue/lib/embeddings/stats.pypolylogue/lib/pricing.pypolylogue/lib/session_payload_documents.pypolylogue/lib/timestamps.pypolylogue/logging.pypolylogue/mcp/payloads.pypolylogue/mcp/server_mutation_tools.pypolylogue/mcp/server_prompts.pypolylogue/mcp/server_support.pypolylogue/mcp/server_tools.pypolylogue/pipeline/ids.pypolylogue/pipeline/payload_types.pypolylogue/pipeline/run_finalization.pypolylogue/pipeline/semantic_capture.pypolylogue/pipeline/services/acquisition_records.pypolylogue/pipeline/services/indexing.pypolylogue/pipeline/services/ingest_batch.pypolylogue/pipeline/services/ingest_worker.pypolylogue/protocols.pypolylogue/readiness.pypolylogue/rendering/core_markdown.pypolylogue/rendering/formatting.pypolylogue/rendering/renderers/__init__.pypolylogue/rendering/renderers/plaintext.pypolylogue/schemas/privacy.pypolylogue/schemas/privacy_config.pypolylogue/site/publication_flow.pypolylogue/sources/assembly.pypolylogue/sources/drive_gateway.pypolylogue/sources/parsers/chatgpt.pypolylogue/sources/parsers/claude_common.pypolylogue/storage/backends/async_sqlite.pypolylogue/storage/backends/async_sqlite_archive.pypolylogue/storage/backends/connection.pypolylogue/storage/backends/queries/conversations_identity.pypolylogue/storage/backends/queries/conversations_writes.pypolylogue/storage/backends/queries/stats.pypolylogue/storage/backends/query_store_archive.pypolylogue/storage/backends/schema_ddl_actions.pypolylogue/storage/backends/schema_ddl_archive.pypolylogue/storage/backends/schema_ddl_product_profiles.pypolylogue/storage/blob_store.pypolylogue/storage/cursor_state.pypolylogue/storage/fts_lifecycle.pypolylogue/storage/query_models.pypolylogue/storage/repository_archive_conversations.pypolylogue/storage/repository_writes.pypolylogue/storage/run_state.pypolylogue/storage/session_product_runtime.pypolylogue/surface_payloads.pytests/unit/cli/test_embed.pytests/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
| - path: polylogue/rendering/renderers/plaintext.py | ||
| loc: 20 | ||
| target: polylogue/rendering/renderers/plaintext.py | ||
| owner: stable |
There was a problem hiding this comment.
🧩 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.yamlRepository: 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 -20Repository: 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 -nRepository: 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.
| # 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"] |
There was a problem hiding this comment.
🛠️ 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.
| # 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".
| 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]" | ||
| ) | ||
|
|
There was a problem hiding this comment.
🧩 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=pyRepository: 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.
| def fail(command: str, message: str) -> NoReturn: | ||
| raise SystemExit(f"{command}: {message}") | ||
| click.echo(f"Error: {message}", err=True) | ||
| raise SystemExit(1) |
There was a problem hiding this comment.
🧩 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.pyRepository: 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 -20Repository: 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=pyRepository: 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 cliRepository: 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 -40Repository: 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.pyRepository: 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.
| 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.
| async with aiosqlite.connect(backend._db_path, timeout=DB_TIMEOUT) as conn: | ||
| os.chmod(backend._db_path, 0o600) | ||
| await configure_connection(conn) | ||
| yield conn |
There was a problem hiding this comment.
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
chmodhere (and remove the now-redundant one inensure_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/*-shmsidecars 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 connAnd 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.
| 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) |
There was a problem hiding this comment.
🧹 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:
- 1: https://man7.org/linux/man-pages/man3/mkstemp.3.html
- 2: https://docs.python.org/3/library/tempfile.html
- 3: https://github.com/python/cpython/blob/main/Lib/tempfile.py
🏁 Script executed:
# Get the file size first to understand how to read it
wc -l polylogue/storage/blob_store.pyRepository: 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.pyRepository: 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.pyRepository: 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.
| 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 |
There was a problem hiding this comment.
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.
| 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.
| exists = await conn.execute( | ||
| "SELECT 1 FROM conversations WHERE conversation_id = ?", | ||
| (conversation_id,), | ||
| ) | ||
| if not await exists.fetchone(): | ||
| continue |
There was a problem hiding this comment.
🧩 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 -80Repository: 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 -30Repository: 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:
- 1: https://aiosqlite.omnilib.dev/en/v0.21.0/api.html
- 2: https://github.com/omnilib/aiosqlite/blob/main/aiosqlite/core.py
- 3: https://aiosqlite.omnilib.dev/en/latest/api.html
- 4: https://aiosqlite.omnilib.dev/en/stable/index.html
- 5: https://github.com/omnilib/aiosqlite/tree/main/aiosqlite
- 6: https://github.com/omnilib/aiosqlite/blob/main/aiosqlite/__init__.py
- 7: __aiter__() and fetchone() are 15x slower than sqlite3 omnilib/aiosqlite#34
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.
| 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).
| 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") |
There was a problem hiding this comment.
🧩 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.pyRepository: 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_*`.
There was a problem hiding this comment.
💡 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".
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]>
ff0723c to
ec13360
Compare
#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]>
… 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]>
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]>
#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]>
… 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]>
|
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. |
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 onRole.normalize()inputs preventsAttributeErroron non-string role values (fixes #469)Hashing — NFC normalization in
_normalize_for_hash(), sentinel tokens inattachment_seed()prevent field-shift collisions, attachment SHA-256 digest included in content hashStorage — FTS trigger DDL fixed to match 6-column schema (fixes #467), triggers use
rowidinstead of UNINDEXED columns (fixes #484),COALESCE(excluded.metadata, conversations.metadata)preserves user tags on content change (fixes #473),quick_readiness_summaryuses correctdb_path(), redundant index removed, misleading comment fixedCLI —
open_verbuses candidate-concatenation pattern matchingshow_verb,show_verbadded (was absent on master per #422),doctor→checkwith hidden alias,fail()unified toclick.echo("Error: ..."), empty archive shows onboarding hint, export help documentsprovider:idMCP —
_clamp_limitupper bound (1000),get_stats_byusesLiteraltype,resolve_idstrict flag for destructive ops,bulk_tag_conversationsitem-count limits + batch TXRendering — heading escape covers all levels (
#through######), CSV injection prevention with_csv_safe(), plaintext renderer addedConfig/security — dead
fts_enabledremoved,max_lengthfalsy fix, XDG path dedup,POLYLOGUE_FORCE_PLAINrespected in logging, db/blobchmod 0o600, manifest path leak fixedBuild —
h2added to Nix deps forhttpx[http2],hatch_build.pysdist fix,typing_extensions→stdlibtyping(18 files)Products —
profile_bucket_daytimezone-aware,records_provenanceISO parse before compare,pricing.pymodel prefix sorted by length,nameadded to privacy content-field denylistDead code —
cli/commands/embed.pydeleted (own docstring admitted it was orphaned)Verification
Closes #488
🤖 Generated with Claude Code
Summary by CodeRabbit
Release Notes
New Features
Bug Fixes
Documentation
Refactor