Repository navigation
fix(reconciliation): restore baseline gates, reconcile closed-scope drift (#944) - #959
Conversation
…rift (#944) Restore the local verification baseline to green and reconcile partially-implemented closed-scope work to a truthful state. Problem ------- `devtools verify --quick` was red: 11 format files, 8 lint errors, 95 mypy errors across 17 files, 10 topology orphans, 2 file-budget overages, 2 missing mutation campaigns, and generated-doc drift. Pytest had 346 failures. Several closed issues landed scaffolding that never reached the intended product closure. Solution -------- Schema v12 — add `input_tokens`, `output_tokens`, `cache_read_tokens`, `cache_write_tokens`, `model_name` to the messages table to match the UPSERT SQL that already referenced them. FTS external-content table fix — replace bare `DELETE FROM messages_fts` with safe alternatives across five code paths: - `messages_fts_ad`/`au` triggers now use the FTS5 `'delete'` command - `delete_conversation_rows_sql` filters via `messages_fts_docsize.id` - `rebuild_fts_index_sync` and `rebuild_fts_index_async` use `'delete-all'` Source name propagation — `conversation_to_record` and `save_conversation_record` now extract `source_name` from `provider_meta.source`. The sync ingest path (`_conversation_tuple`, `_resolved_conversation_tuple`, `_conversation_tuple_with_hash`) includes the 15th tuple element. Config surface polish: - API enabled by default (`--no-api` opt-out); systemd unit updated - Pruned dead config keys: `hooks.enabled`, `hooks.sidecar_dir`, `additional_sources` (read by nothing in the codebase) - `_merge_toml` and `format_config_toml` now use short-key mapping so generated TOML round-trips through the NixOS module - `embedding_max_cost_usd` default raised to $5 soft cap - `polylogue config` fixed (`.raw` dispatch, markup-safe rendering) Bug fixes surfaced during the reconciliation pass: - Daemon facets handler: sync `def` with nested `asyncio.run` → `async def` - Daemon pidfile: move `_pidfile_path` assignment after flock acquisition - `ConversationFormatter`: honor `db_path` kwarg, fall back to canonical XDG - `PlainConsole.print`: respect `markup=False` kwarg - `compute_session_cost` import path: `archive.cost.compute` → `archive.semantic.cost_compute` Verification ------------ ``` $ devtools verify --quick verify: all checks passed $ pytest --ignore=tests/integration --ignore=tests/benchmarks 5859 passed, 1 xfailed ``` The single xfail is `test_empty_routing_fails` — routing not yet implemented per #594 (pre-existing, not a regression). Closed-issue matrix in the #944 closing comment. Co-Authored-By: Claude Opus 4.7 <[email protected]>
|
Warning Rate limit exceeded
You’ve run out of usage credits. Purchase more in the billing tab. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (12)
📝 WalkthroughWalkthroughRemoves CLI tail overlay; introduces layered config and daemon --no-* flags; bumps schema to v12 with token/model fields and FTS safety; propagates source_name and token/cost fields through pipeline/storage; updates renderers, logging, docs, and tests. ChangesCore realignment and schema v12
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related issues
Possibly related PRs
Suggested labels
Poem
✨ Finishing Touches🧪 Generate unit tests (beta)
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 197af02708
ℹ️ 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".
Problem: Lynchpin sync consumers had to fall back to incomplete SyncPolylogue coverage and N-at-a-time message reads for transcript windows, making refreshes slower and leakier than the async facade surface. What changed: added the missing sync bridges for the current read/query/status/insight-readiness surface, exposed bulk_get_messages on the async and sync facades, and threaded role/date filters through the existing SQLite batch message read path so consumers get one IN-query rather than per-conversation fetches. Verification: ruff check on all changed files; mypy on all changed files; pytest tests/unit/core/test_sync_surface_runtime.py tests/unit/storage/test_message_query_reads.py tests/unit/core/test_facade_api.py -q --no-header --tb=short. Ref #723. Ref #726.
There was a problem hiding this comment.
Actionable comments posted: 20
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (6)
tests/unit/core/test_maintenance_targets.py (1)
13-18: 🧹 Nitpick | 🔵 Trivial | ⚡ Quick win
orphaned_blobsmode membership is not exercised.
test_maintenance_target_catalog_groups_targets_by_moderelies on the importedMAINTENANCE_TARGET_NAMES,SAFE_REPAIR_TARGETS, andCLEANUP_TARGETSconstants, so it will automatically coverorphaned_blobsif those constants are updated. However, there is no explicit assertion thatorphaned_blobsbelongs to a specific mode (REPAIRorCLEANUP). If the new target is accidentally omitted from both mode sets (only added to the names list), this test suite would not catch that gap.Consider adding a targeted assertion:
🛡️ Suggested additional assertion
def test_maintenance_target_catalog_groups_targets_by_mode() -> None: catalog = build_maintenance_target_catalog() assert catalog.names() == MAINTENANCE_TARGET_NAMES assert catalog.names_for_mode(MaintenanceTargetMode.REPAIR) == SAFE_REPAIR_TARGETS assert catalog.names_for_mode(MaintenanceTargetMode.CLEANUP) == CLEANUP_TARGETS + # Ensure every registered name is assigned to exactly one mode. + all_mode_names = set(SAFE_REPAIR_TARGETS) | set(CLEANUP_TARGETS) + assert set(MAINTENANCE_TARGET_NAMES) == all_mode_names, ( + "Some targets are not assigned to any mode: " + f"{set(MAINTENANCE_TARGET_NAMES) - all_mode_names}" + )🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/unit/core/test_maintenance_targets.py` around lines 13 - 18, Add an explicit check that the new "orphaned_blobs" target is assigned to a mode: in test_maintenance_target_catalog_groups_targets_by_mode, after the existing assertions, assert that "orphaned_blobs" appears in the union of catalog.names_for_mode(MaintenanceTargetMode.REPAIR) and catalog.names_for_mode(MaintenanceTargetMode.CLEANUP) (using the existing catalog.names_for_mode method and MaintenanceTargetMode enum) so a target added to MAINTENANCE_TARGET_NAMES but omitted from both mode sets will fail the test.README.md (2)
45-46:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winUpdate README examples to reflect API-enabled-by-default behavior.
The three
polylogued run --enable-apiexamples (lines 45-46, 63-64, 126-128) use a non-existent flag. The CLI uses--no-apito disable the HTTP API, which is enabled by default. Simplify these topolylogued runor explicitly document the--no-apiopt-out pattern.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@README.md` around lines 45 - 46, Replace the incorrect CLI examples that use the non-existent flag "polylogued run --enable-api" with the correct default-enabled form "polylogued run" and/or add a note about the opt-out flag "--no-api"; update every occurrence (the examples using "polylogued run --enable-api") to either remove the "--enable-api" flag or explicitly document that the HTTP API is enabled by default and can be disabled with "--no-api".
45-46:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winRemove stale
--enable-apiflag from documentation examples.The API is enabled by default with opt-out via
--no-api. Lines 45, 63, and 126 showpolylogued run --enable-api, which doesn't exist and will cause an "unrecognized argument" error. Either remove the flag (API is on by default) or use--no-apiif disabling is needed.Line 82 already shows the correct pattern:
polylogued runwithout any API flag.Also applies to: 63-64, 127-128
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@README.md` around lines 45 - 46, Remove the stale --enable-api flag from all documentation examples that use "polylogued run --enable-api" and replace them with the correct default form "polylogued run"; if the intent in any example was to show disabling the API, change the flag to the opt-out form "--no-api" instead, updating every occurrence of "--enable-api" to either "polylogued run" or "polylogued run --no-api" as appropriate.polylogue/storage/sqlite/schema_ddl_archive.py (1)
268-281:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winFTS5 delete/update triggers omit
WHERE old.text IS NOT NULLguard.The insert trigger (
messages_fts_ai) only indexes rows wheretext IS NOT NULL. However, the delete and update triggers unconditionally issue a'delete'command — even for rows that were never indexed (becauseold.textwasNULLat insert time). For FTS5 external-content tables this is mostly benign, but it may silently corrupt themessages_fts_docsizetable with a phantom delete entry for a rowid that was never written.Consider mirroring the insert guard:
🛡️ Proposed guard for delete trigger
CREATE TRIGGER IF NOT EXISTS messages_fts_ad AFTER DELETE ON messages BEGIN + SELECT CASE WHEN old.text IS NOT NULL THEN ( INSERT INTO messages_fts(messages_fts, rowid, message_id, conversation_id, text) - VALUES('delete', old.rowid, old.message_id, old.conversation_id, old.text); + VALUES('delete', old.rowid, old.message_id, old.conversation_id, old.text) + ) END; END;Or more idiomatically (SQLite 3.38+):
CREATE TRIGGER IF NOT EXISTS messages_fts_ad AFTER DELETE ON messages BEGIN - INSERT INTO messages_fts(messages_fts, rowid, message_id, conversation_id, text) - VALUES('delete', old.rowid, old.message_id, old.conversation_id, old.text); + INSERT INTO messages_fts(messages_fts, rowid, message_id, conversation_id, text) + SELECT 'delete', old.rowid, old.message_id, old.conversation_id, old.text + WHERE old.text IS NOT NULL; END;Same pattern applies to the
'delete'step in the update trigger.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@polylogue/storage/sqlite/schema_ddl_archive.py` around lines 268 - 281, The FTS5 delete/update triggers (messages_fts_ad and messages_fts_au) unconditionally insert a 'delete' row even when the original row was never indexed; update the messages_fts_ad trigger and the first INSERT in messages_fts_au to include the same guard used by the insert trigger (e.g., add a WHERE old.text IS NOT NULL) so the 'delete' command only runs for rows that were indexed (mirror the messages_fts_ai insert guard).docs/daemon.md (1)
298-300:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winStale
--enable-apiflag in systemd unit example.The PR changes the API from opt-in (
--enable-api) to opt-out (--no-api). The systemdExecStartexample on Line 299 still passes--enable-api, which is now either an unrecognised flag or dead. Users copy-pasting this snippet will hit a startup error.📝 Proposed fix
-ExecStart=%h/.nix-profile/bin/polylogued run --enable-api --api-port 8766 +ExecStart=%h/.nix-profile/bin/polylogued run --api-port 8766🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/daemon.md` around lines 298 - 300, The systemd unit example's ExecStart uses the stale flag "--enable-api" which is now removed in favor of an opt-out "--no-api"; update the ExecStart example (the line starting with ExecStart=%h/.nix-profile/bin/polylogued run ...) to remove "--enable-api" and, if the intent is to enable the API by default, omit any flag or explicitly show "--no-api" only when disabling it so copy-pasting won't cause an unrecognized-flag startup error.polylogue/core/common.py (1)
40-50:⚠️ Potential issue | 🟠 Major | ⚡ Quick win
source_namecan fail to persist on conflict-only updatesLine 40 adds
source_nameto the update set, but the conflictWHEREclause (Lines 42–50) does not includesource_namechange detection. Ifsource_nameis the only changed field, no update happens.Suggested fix
WHERE content_hash != excluded.content_hash OR IFNULL(title, '') != IFNULL(excluded.title, '') OR IFNULL(created_at, '') != IFNULL(excluded.created_at, '') OR IFNULL(updated_at, '') != IFNULL(excluded.updated_at, '') OR IFNULL(provider_meta, '') != IFNULL(excluded.provider_meta, '') OR IFNULL(parent_conversation_id, '') != IFNULL(excluded.parent_conversation_id, '') OR IFNULL(branch_type, '') != IFNULL(excluded.branch_type, '') OR IFNULL(raw_id, '') != IFNULL(excluded.raw_id, '') + OR IFNULL(source_name, '') != IFNULL(NULLIF(excluded.source_name, ''), IFNULL(source_name, '')) OR IFNULL(sort_key, 0) != IFNULL(excluded.sort_key, 0)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@polylogue/core/common.py` around lines 40 - 50, The INSERT ... ON CONFLICT update block sets source_name = COALESCE(NULLIF(excluded.source_name, ''), conversations.source_name) but the conflict WHERE clause that decides whether to apply the UPDATE doesn't check changes to source_name, so a change to source_name alone won't persist; update the WHERE condition (the OR list comparing IFNULL(..., '')) to include a comparison for source_name (e.g., OR IFNULL(source_name, '') != IFNULL(excluded.source_name, '')) so the UPDATE will run when source_name changes; target the statements around the conversations update (the COALESCE(NULLIF(excluded.source_name, ''), conversations.source_name) assignment and the conflict WHERE OR comparisons) to add this comparison.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@nix/module.nix`:
- Around line 176-179: Add a new NixOS module option named extraArgs (mkOption
type = types.listOf types.str, default = []) and wire it into the ExecStart
string so callers can pass flags like "--no-api" without overwriting the
generated command; update ExecStart from "${cfg.package}/bin/polylogued run" to
something like "${cfg.package}/bin/polylogued run ${lib.concatStringsSep " "
cfg.extraArgs}" (ensure you import/use lib.concatStringsSep and keep extraArgs
defaulting to []).
In `@polylogue/archive/message/artifacts.py`:
- Around line 91-94: The current scan uses any(line.startswith("<file path=")
for line in stripped.splitlines()), which allocates a list of lines; replace it
with a compiled multiline regex (reuse the existing _CONTENTS_OF_LINE_RE pattern
style) that matches "^<file path=" across lines and call its .search(stripped)
to detect a match; update the check that returns MessageType.CONTEXT to use that
compiled regex (referencing the same stripped variable and MessageType.CONTEXT)
so the behavior is identical but avoids splitlines allocation and is consistent
with _CONTENTS_OF_LINE_RE.
In `@polylogue/archive/semantic/outlook.py`:
- Around line 165-168: _as_float currently calls float(cast(float, value)) and
will raise on empty strings or malformed inputs; update _as_float to be tolerant
by first treating None, empty string, and whitespace-only strings as returning
the provided default, then attempt conversion inside a try/except catching
ValueError and TypeError and returning default on failure; also support numeric
inputs (int/float) by returning them directly (or cast to float) so
ingestion-derived malformed or missing numeric fields don't hard-fail.
- Line 83: The cycle end calculation uses now.month instead of the provided
start, causing incorrect end dates when cycle_start is supplied; update the
logic that sets end (currently: end = start.replace(year=start.year + 1,
month=1) if now.month == 12 else start.replace(month=start.month + 1)) to base
the December check on start.month (i.e., use start.month == 12) so the roll-over
to January increments start.year and otherwise advances start.month; adjust any
surrounding references to now only if they intended current-time behavior,
otherwise keep using start and preserve variable names start, end, now, and
cycle_start for clarity.
In `@polylogue/archive/session/models.py`:
- Around line 115-122: The new cost/token fields declared on the SessionProfile
dataclass (total_input_tokens, total_output_tokens, total_cache_read_tokens,
total_cache_write_tokens, total_credit_cost, cost_provenance,
per_model_cost_json) are missing from SessionProfile.to_dict and
SessionProfile.from_dict, causing silent loss on serialization/deserialization;
update SessionProfile.to_dict to include those fields in the returned dict (same
key names as the attributes) and update SessionProfile.from_dict to read those
keys from the input dict (use dict.get(..., <current default>) to preserve
existing defaults) so round-trips retain cost/token data.
In `@polylogue/daemon/convergence_stages.py`:
- Around line 481-485: The helper _embedding_config_enabled currently calls
load_polylogue_config() on every convergence tick causing repeated I/O; instead,
load the config once when the stage is constructed (inside make_embed_stage) and
close over that value (or store it on the stage object) so the check and execute
closures reference the cached config (or a small TTL-cached wrapper) rather than
calling load_polylogue_config() directly; update references to
cfg.embedding_enabled and cfg.voyage_api_key inside _embedding_config_enabled
(or replace _embedding_config_enabled with a closure) so they use the cached
config instance created by make_embed_stage.
In `@polylogue/pipeline/services/ingest_worker.py`:
- Around line 794-797: The current code uses
str(conversation.provider_meta.get("source", "")) which will convert
non-string/None values into literal strings like "None"; instead, extract
provider_meta["source"] into a local (e.g., src =
conversation.provider_meta.get("source")) and only assign to source_name if
isinstance(src, str) (optionally src.strip() to normalize); otherwise set
source_name = "" so non-string or null values are not persisted. Update the
block referencing source_name and conversation.provider_meta accordingly,
removing the unconditional str(...) conversion.
In `@polylogue/rendering/core_formatter.py`:
- Around line 64-68: The current logic unconditionally falls back to
archive_root / "polylogue.db" when resolved from default_db_path() is missing;
update the block around resolved, default_db_path(), and the
SQLiteBackend(db_path=resolved) instantiation so that after setting resolved =
default_db_path() you check existence of that path and only set resolved =
archive_root / "polylogue.db" if that legacy file also exists; if neither
exists, keep resolved as None (or raise/log a clear error) and avoid passing a
non-existent path into SQLiteBackend(db_path=resolved). Ensure the changes touch
the resolved assignment and the code that creates SQLiteBackend to prevent
silently pointing at a missing DB.
In `@polylogue/storage/repository/archive/writes/conversations.py`:
- Around line 153-154: The code currently does source_name_val =
str(provider_meta.get("source", "")) which turns None or objects into literal
string representations; change both occurrences to only accept real strings:
read val = provider_meta.get("source") and set source_name_val = val if
isinstance(val, str) else "" so non-string or None values are normalized to an
empty string rather than being stringified.
In `@polylogue/storage/sqlite/queries/conversations_writes.py`:
- Around line 25-30: The code is coercing provider_meta["source"] with str(),
which will turn None or non-string values into literal strings like "None" and
corrupt source_name; instead, retrieve the raw value from record.provider_meta
(use record.provider_meta.get("source")) into a temporary variable, and only
assign it to source_name if it's a non-empty string (e.g., isinstance(val, str)
and val); otherwise leave source_name unset/None so downstream query/filter
semantics remain correct (update the logic around source_name and
record.provider_meta in conversations_writes.py).
In `@polylogue/storage/sqlite/schema_ddl.py`:
- Line 60: Update the inline comment attached to SCHEMA_VERSION = 12 to
reference the correct PR number: change the trailing "(`#943`)" to "(`#944`)" so the
schema version comment accurately reflects this PR; modify the comment text
immediately following the SCHEMA_VERSION constant to correct the PR identifier.
In `@tests/infra/storage_records.py`:
- Around line 421-433: The conflict WHERE predicate for the upsert is missing
the has_thinking comparison so updates are skipped when only that flag changes;
update the WHERE clause used with the DO UPDATE SET to include a comparison for
has_thinking (e.g., add "OR has_thinking != excluded.has_thinking" or
IFNULL-style comparison consistent with the rest) so the upsert detects and
applies changes to has_thinking in the same statement.
In `@tests/unit/cli/test_check.py`:
- Around line 330-334: The test currently accepts index_check["status"] being
"ok", which masks regressions; change the assertion to require the dedicated
drift signal instead by asserting that the fts_sync check reports "warning"
(e.g. replace the index_check status assertion with an assertion like
checks["fts_sync"]["status"] == "warning" or otherwise locate the fts_sync check
and assert its ["status"] == "warning"), leaving index_check handling unchanged
if needed.
In `@tests/unit/cli/test_status.py`:
- Around line 151-152: Replace the overly permissive assertion that checks for
any "watching" substring with a precise expectation on the new wording: update
the assertion that inspects the variable combined to assert the exact phrase
(for example assert "watching 2 sources" in combined.lower()) or, if the source
count is dynamic, assert against a strict pattern such as a regex like
r"watching \d+ sources" to ensure the new rendering logic is actually exercised
(locate and modify the assertion that currently reads: assert "watching" in
combined.lower() or "no conversations ingested yet" in combined.lower()).
In `@tests/unit/daemon/test_daemon_status.py`:
- Around line 187-190: The test currently allows any number of freshness probe
invocations by asserting freshness_info.call_count >= 1; change this to assert a
bounded range to catch caching regressions—replace that assertion with one that
checks freshness_info.call_count is at least 1 and at most 2 (e.g., 1 <=
freshness_info.call_count <= 2) so the test enforces reuse with at most one
additional deep-band probe in test_daemon_status.py where freshness_info is
used.
In `@tests/unit/devtools/test_artifact_graph.py`:
- Around line 297-299: The current assertion uses all(...) over
payload["scenario_coverage"]["uncovered_operations"], which passes vacuously for
an empty list; update the test to first assert that
payload["scenario_coverage"]["uncovered_operations"] is present and non-empty
when mutations are expected (e.g., assert
payload["scenario_coverage"]["uncovered_operations"]), then assert that every
name starts with "mutate-" using the existing all(...) check so the test fails
if the list is missing or empty as well as if any item does not match.
In `@tests/unit/operations/test_specs.py`:
- Around line 43-49: The mutation ops listed ("mutate-add-tag",
"mutate-remove-tag", "mutate-set-metadata", "mutate-delete-metadata",
"mutate-delete-conversation", "mutate-bulk-tag-conversations") are only
membership-checked; add contract assertions in the test
(tests/unit/operations/test_specs.py) that each of these operations has kind ==
OperationKind.MUTATION and mutates_state is True (and optionally validate
produces/path_targets if relevant) so the test fails on silent contract drift.
Locate the test that iterates over operation specs and, for each of the six
mutation op ids, assert the op_spec.kind equals OperationKind.MUTATION and
op_spec.mutates_state is True.
In `@tests/unit/pipeline/test_prepare.py`:
- Around line 36-40: The test relaxes idempotency checks but forgot attachments:
add an aggregate assertion like the existing ones that verifies
second.attachments + second.skipped_attachments == 1 so the second-pass
accounting for attachments is covered; update the test around the other
aggregate assertions (referencing the second variable and its attachments and
skipped_attachments properties) to include this check.
In `@tests/unit/storage/test_cost_queries.py`:
- Around line 42-52: The test_subscription_credit_cost is too weak with only
assert cost > 0; update the test to assert the per-component credit breakdown
returned by compute_credit_cost rather than just a scalar—call
compute_credit_cost("claude-sonnet-4-6", input_tokens=1000, output_tokens=500)
and assert expected values or ranges for input_credits, output_credits and
total_credits (and/or that total_credits == input_credits + output_credits) so
regressions that drop or conflate components are caught; reference
compute_credit_cost and the test_subscription_credit_cost function when making
the change.
In `@tests/unit/storage/test_vec.py`:
- Around line 375-379: The empty-embedding test currently only asserts result ==
[] but must also verify the "close connections" contract: update the test around
the empty-embedding branch to detect whether a connection was opened (e.g.,
spy/mocking call to the provider's connection open method or the connection
object created in this test) and assert that if such an open occurred, the
corresponding close/cleanup method (e.g., connection.close or
provider.close_connection) was called before the function returned; keep the
existing result == [] assertion and add the conditional assertion that the close
call count is >=1 if the open call count is >=1 so the connection is always
closed when opened.
---
Outside diff comments:
In `@docs/daemon.md`:
- Around line 298-300: The systemd unit example's ExecStart uses the stale flag
"--enable-api" which is now removed in favor of an opt-out "--no-api"; update
the ExecStart example (the line starting with
ExecStart=%h/.nix-profile/bin/polylogued run ...) to remove "--enable-api" and,
if the intent is to enable the API by default, omit any flag or explicitly show
"--no-api" only when disabling it so copy-pasting won't cause an
unrecognized-flag startup error.
In `@polylogue/core/common.py`:
- Around line 40-50: The INSERT ... ON CONFLICT update block sets source_name =
COALESCE(NULLIF(excluded.source_name, ''), conversations.source_name) but the
conflict WHERE clause that decides whether to apply the UPDATE doesn't check
changes to source_name, so a change to source_name alone won't persist; update
the WHERE condition (the OR list comparing IFNULL(..., '')) to include a
comparison for source_name (e.g., OR IFNULL(source_name, '') !=
IFNULL(excluded.source_name, '')) so the UPDATE will run when source_name
changes; target the statements around the conversations update (the
COALESCE(NULLIF(excluded.source_name, ''), conversations.source_name) assignment
and the conflict WHERE OR comparisons) to add this comparison.
In `@polylogue/storage/sqlite/schema_ddl_archive.py`:
- Around line 268-281: The FTS5 delete/update triggers (messages_fts_ad and
messages_fts_au) unconditionally insert a 'delete' row even when the original
row was never indexed; update the messages_fts_ad trigger and the first INSERT
in messages_fts_au to include the same guard used by the insert trigger (e.g.,
add a WHERE old.text IS NOT NULL) so the 'delete' command only runs for rows
that were indexed (mirror the messages_fts_ai insert guard).
In `@README.md`:
- Around line 45-46: Replace the incorrect CLI examples that use the
non-existent flag "polylogued run --enable-api" with the correct default-enabled
form "polylogued run" and/or add a note about the opt-out flag "--no-api";
update every occurrence (the examples using "polylogued run --enable-api") to
either remove the "--enable-api" flag or explicitly document that the HTTP API
is enabled by default and can be disabled with "--no-api".
- Around line 45-46: Remove the stale --enable-api flag from all documentation
examples that use "polylogued run --enable-api" and replace them with the
correct default form "polylogued run"; if the intent in any example was to show
disabling the API, change the flag to the opt-out form "--no-api" instead,
updating every occurrence of "--enable-api" to either "polylogued run" or
"polylogued run --no-api" as appropriate.
In `@tests/unit/core/test_maintenance_targets.py`:
- Around line 13-18: Add an explicit check that the new "orphaned_blobs" target
is assigned to a mode: in
test_maintenance_target_catalog_groups_targets_by_mode, after the existing
assertions, assert that "orphaned_blobs" appears in the union of
catalog.names_for_mode(MaintenanceTargetMode.REPAIR) and
catalog.names_for_mode(MaintenanceTargetMode.CLEANUP) (using the existing
catalog.names_for_mode method and MaintenanceTargetMode enum) so a target added
to MAINTENANCE_TARGET_NAMES but omitted from both mode sets will fail the test.
🪄 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: 4e740285-7353-465c-b0ab-9d719b30bbbe
📒 Files selected for processing (116)
.gitignoreCHANGELOG.mdREADME.mdbrowser-extension/eslint.config.jsdevtools/verify_slos.pydocs/cli-reference.mddocs/configuration.mddocs/daemon.mddocs/design/mk2/design-canvas/artboard-states.jsxdocs/plans/campaign-coverage.yamldocs/plans/file-size-budgets.yamldocs/plans/schema-inventory.mddocs/plans/topology-target.yamldocs/test-quality-workflows.mddocs/topology-status.mddocs/verification-catalog.mdnix/module.nixpolylogue/api/__init__.pypolylogue/archive/conversation/runtime.pypolylogue/archive/conversation/summary_runtime.pypolylogue/archive/conversation/tail_overlay.pypolylogue/archive/message/artifacts.pypolylogue/archive/semantic/cost_compute.pypolylogue/archive/semantic/cost_records.pypolylogue/archive/semantic/outlook.pypolylogue/archive/semantic/subscription_models.pypolylogue/archive/semantic/subscription_pricing.pypolylogue/archive/session/models.pypolylogue/archive/session/runtime.pypolylogue/cli/click_app.pypolylogue/cli/click_command_registration.pypolylogue/cli/click_option_groups.pypolylogue/cli/commands/config.pypolylogue/cli/commands/cost.pypolylogue/cli/query.pypolylogue/cli/query_progress.pypolylogue/cli/select.pypolylogue/config.pypolylogue/core/common.pypolylogue/daemon/cli.pypolylogue/daemon/convergence_stages.pypolylogue/daemon/http.pypolylogue/insights/storage.pypolylogue/logging.pypolylogue/pipeline/materialization_runtime.pypolylogue/pipeline/services/ingest_batch/_core.pypolylogue/pipeline/services/ingest_worker.pypolylogue/pipeline/tail_overlay.pypolylogue/rendering/core_formatter.pypolylogue/rendering/renderers/html.pypolylogue/rendering/renderers/markdown.pypolylogue/sources/drive/auth.pypolylogue/storage/fts/fts_lifecycle.pypolylogue/storage/fts/sql.pypolylogue/storage/insights/session/records.pypolylogue/storage/insights/session/runtime.pypolylogue/storage/insights/session/status.pypolylogue/storage/repository/archive/writes/conversations.pypolylogue/storage/sqlite/queries/attachment_mutations.pypolylogue/storage/sqlite/queries/conversations_reads.pypolylogue/storage/sqlite/queries/conversations_writes.pypolylogue/storage/sqlite/schema_ddl.pypolylogue/storage/sqlite/schema_ddl_archive.pypolylogue/storage/sqlite/schema_ddl_insight_profiles.pypolylogue/surfaces/payloads.pypolylogue/ui/facade_console.pytests/baselines/showcase/help-main.txttests/benchmarks/test_daemon_convergence.pytests/benchmarks/test_reader_api.pytests/data/witnesses/mcp-tool-schemas.jsontests/infra/mcp.pytests/infra/storage_records.pytests/integration/test_tui_dashboard.pytests/unit/browser_capture/test_receiver_contract.pytests/unit/cli/__snapshots__/test_terminal_snapshots.ambrtests/unit/cli/test_check.pytests/unit/cli/test_check_support_runtime.pytests/unit/cli/test_click_app.pytests/unit/cli/test_command_aux_runtime.pytests/unit/cli/test_insights.pytests/unit/cli/test_output_contracts.pytests/unit/cli/test_query_exec.pytests/unit/cli/test_select.pytests/unit/cli/test_status.pytests/unit/cli/test_tail_query_runtime.pytests/unit/core/test_artifact_graph.pytests/unit/core/test_artifact_specs.pytests/unit/core/test_health_core.pytests/unit/core/test_maintenance_targets.pytests/unit/core/test_paths.pytests/unit/core/test_query_fields.pytests/unit/daemon/test_convergence_stages.pytests/unit/daemon/test_daemon_cli.pytests/unit/daemon/test_daemon_status.pytests/unit/daemon/test_web_reader.pytests/unit/devtools/test_artifact_graph.pytests/unit/devtools/test_quality_registry.pytests/unit/devtools/test_scenario_coverage.pytests/unit/mcp/test_mcp_edge_cases.pytests/unit/mcp/test_tool_contracts.pytests/unit/operations/test_specs.pytests/unit/pipeline/test_ingest_batch.pytests/unit/pipeline/test_prepare.pytests/unit/pipeline/test_prepare_records.pytests/unit/pipeline/test_tail_overlay_runtime.pytests/unit/showcase/test_exercise_catalog.pytests/unit/storage/test_backend.pytests/unit/storage/test_cost_queries.pytests/unit/storage/test_embedding_stats.pytests/unit/storage/test_fts5.pytests/unit/storage/test_raw_ingest_artifacts.pytests/unit/storage/test_session_insight_status_descriptors.pytests/unit/storage/test_vec.pytests/unit/test_logging_runtime.pytests/unit/test_protocol_conformance.pytests/unit/ui/test_tui.py
💤 Files with no reviewable changes (17)
- tests/unit/devtools/test_quality_registry.py
- polylogue/cli/click_option_groups.py
- tests/unit/cli/test_tail_query_runtime.py
- polylogue/insights/storage.py
- polylogue/archive/conversation/runtime.py
- docs/plans/schema-inventory.md
- tests/unit/core/test_health_core.py
- polylogue/archive/semantic/subscription_models.py
- polylogue/archive/conversation/tail_overlay.py
- tests/unit/pipeline/test_tail_overlay_runtime.py
- tests/unit/showcase/test_exercise_catalog.py
- polylogue/pipeline/tail_overlay.py
- tests/unit/core/test_artifact_specs.py
- polylogue/archive/conversation/summary_runtime.py
- tests/unit/cli/test_select.py
- polylogue/cli/click_app.py
- polylogue/surfaces/payloads.py
👮 Files not reviewed due to content moderation or server errors (8)
- polylogue/storage/sqlite/schema_ddl_insight_profiles.py
- tests/unit/mcp/test_tool_contracts.py
- tests/unit/storage/test_fts5.py
- tests/benchmarks/test_daemon_convergence.py
- docs/configuration.md
- tests/unit/storage/test_backend.py
- polylogue/sources/drive/auth.py
- polylogue/config.py
| # `polylogued run` enables watch + browser-capture + HTTP API by default. | ||
| # Pass --no-watch / --no-browser-capture / --no-api at the unit level if | ||
| # a deployment needs a narrower component set. | ||
| ExecStart = "${cfg.package}/bin/polylogued run"; |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial | ⚡ Quick win
No module option surfaces the documented --no-* flags.
The inline comments tell operators to "pass --no-watch / --no-browser-capture / --no-api at the unit level," but ExecStart is hardcoded to polylogued run with no configurable attribute to append those flags. A NixOS consumer who wants a narrower component set must override serviceConfig.ExecStart entirely — losing the generated config path interpolation — or use systemd.services.polylogued.serviceConfig.ExecStart = lib.mkForce "...".
Consider exposing a small option such as:
+ extraArgs = mkOption {
+ type = types.listOf types.str;
+ default = [];
+ description = "Extra arguments passed to `polylogued run`, e.g. [\"--no-api\"].";
+ };and wiring it in ExecStart:
- ExecStart = "${cfg.package}/bin/polylogued run";
+ ExecStart = "${cfg.package}/bin/polylogued run ${lib.escapeShellArgs cfg.settings.extraArgs}";🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@nix/module.nix` around lines 176 - 179, Add a new NixOS module option named
extraArgs (mkOption type = types.listOf types.str, default = []) and wire it
into the ExecStart string so callers can pass flags like "--no-api" without
overwriting the generated command; update ExecStart from
"${cfg.package}/bin/polylogued run" to something like
"${cfg.package}/bin/polylogued run ${lib.concatStringsSep " " cfg.extraArgs}"
(ensure you import/use lib.concatStringsSep and keep extraArgs defaulting to
[]).
| # <file path=...> markers often appear on a non-first line in multiline | ||
| # context-dump messages. Scan all lines rather than just the first. | ||
| if any(line.startswith("<file path=") for line in stripped.splitlines()): | ||
| return MessageType.CONTEXT |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial | 💤 Low value
Consider a compiled multiline regex, consistent with the existing _CONTENTS_OF_LINE_RE pattern.
The any(line.startswith(...) for line in stripped.splitlines()) approach works correctly, but splitlines() materialises the full line list in memory for every call. The file already uses a compiled multiline regex (_CONTENTS_OF_LINE_RE) for an equivalent "scan all lines" heuristic, which avoids the allocation and is slightly more consistent:
♻️ Proposed refactor
+_FILE_PATH_LINE_RE = re.compile(r"^<file path=", re.MULTILINE)
+
...
- # <file path=...> markers often appear on a non-first line in multiline
- # context-dump messages. Scan all lines rather than just the first.
- if any(line.startswith("<file path=") for line in stripped.splitlines()):
+ # <file path=...> markers often appear on a non-first line in multiline
+ # context-dump messages. Scan all lines rather than just the first.
+ if _FILE_PATH_LINE_RE.search(stripped):
return MessageType.CONTEXT🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@polylogue/archive/message/artifacts.py` around lines 91 - 94, The current
scan uses any(line.startswith("<file path=") for line in stripped.splitlines()),
which allocates a list of lines; replace it with a compiled multiline regex
(reuse the existing _CONTENTS_OF_LINE_RE pattern style) that matches "^<file
path=" across lines and call its .search(stripped) to detect a match; update the
check that returns MessageType.CONTEXT to use that compiled regex (referencing
the same stripped variable and MessageType.CONTEXT) so the behavior is identical
but avoids splitlines allocation and is consistent with _CONTENTS_OF_LINE_RE.
| end = start.replace(year=start.year + 1, month=1) | ||
| else: | ||
| end = start.replace(month=start.month + 1) | ||
| end = start.replace(year=start.year + 1, month=1) if now.month == 12 else start.replace(month=start.month + 1) |
There was a problem hiding this comment.
Cycle end calculation is keyed to now.month instead of start.month
Line 83 can compute the wrong cycle end when cycle_start is provided and differs from the current month context.
Suggested fix
- end = start.replace(year=start.year + 1, month=1) if now.month == 12 else start.replace(month=start.month + 1)
+ end = start.replace(year=start.year + 1, month=1) if start.month == 12 else start.replace(month=start.month + 1)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@polylogue/archive/semantic/outlook.py` at line 83, The cycle end calculation
uses now.month instead of the provided start, causing incorrect end dates when
cycle_start is supplied; update the logic that sets end (currently: end =
start.replace(year=start.year + 1, month=1) if now.month == 12 else
start.replace(month=start.month + 1)) to base the December check on start.month
(i.e., use start.month == 12) so the roll-over to January increments start.year
and otherwise advances start.month; adjust any surrounding references to now
only if they intended current-time behavior, otherwise keep using start and
preserve variable names start, end, now, and cycle_start for clarity.
| def _as_float(value: object, default: float = 0.0) -> float: | ||
| if value is None: | ||
| return default | ||
| return float(cast(float, value)) |
There was a problem hiding this comment.
_as_float can now hard-fail on empty/invalid numeric fields
Line 168 raises on values like "" or malformed strings, which can break outlook computation for partial data. This helper is used on ingestion-derived fields and should be tolerant.
Suggested fix
def _as_float(value: object, default: float = 0.0) -> float:
if value is None:
return default
- return float(cast(float, value))
+ try:
+ return float(cast(float, value))
+ except (TypeError, ValueError):
+ return default🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@polylogue/archive/semantic/outlook.py` around lines 165 - 168, _as_float
currently calls float(cast(float, value)) and will raise on empty strings or
malformed inputs; update _as_float to be tolerant by first treating None, empty
string, and whitespace-only strings as returning the provided default, then
attempt conversion inside a try/except catching ValueError and TypeError and
returning default on failure; also support numeric inputs (int/float) by
returning them directly (or cast to float) so ingestion-derived malformed or
missing numeric fields don't hard-fail.
| # Cost / token attribution (added by #942/#943 cost forecasting work). | ||
| total_input_tokens: int = 0 | ||
| total_output_tokens: int = 0 | ||
| total_cache_read_tokens: int = 0 | ||
| total_cache_write_tokens: int = 0 | ||
| total_credit_cost: float = 0.0 | ||
| cost_provenance: str = "unknown" | ||
| per_model_cost_json: str = "{}" |
There was a problem hiding this comment.
to_dict() / from_dict() not updated — new fields silently dropped on round-trip.
The seven new cost/token fields (total_input_tokens, total_output_tokens, total_cache_read_tokens, total_cache_write_tokens, total_credit_cost, cost_provenance, per_model_cost_json) are declared on the dataclass but absent from both to_dict() (lines 128–175) and from_dict() (lines 177–233).
Consequences:
- Any consumer calling
profile.to_dict()will silently omit all token/cost attribution from the serialized payload (export, API response, backup, etc.). - Any consumer calling
SessionProfile.from_dict(payload)will always reconstruct defaults (0 / 0.0 / "unknown" / "{}") regardless of what the source payload contains, making deserialization lossy.
🛠️ Proposed fix — add fields to both methods
In to_dict(), after "timing_provenance": self.timing_provenance, add:
+ "total_input_tokens": self.total_input_tokens,
+ "total_output_tokens": self.total_output_tokens,
+ "total_cache_read_tokens": self.total_cache_read_tokens,
+ "total_cache_write_tokens": self.total_cache_write_tokens,
+ "total_credit_cost": self.total_credit_cost,
+ "cost_provenance": self.cost_provenance,
+ "per_model_cost_json": self.per_model_cost_json,In from_dict(), after timing_provenance=... add:
+ total_input_tokens=coerce_int(payload.get("total_input_tokens"), 0),
+ total_output_tokens=coerce_int(payload.get("total_output_tokens"), 0),
+ total_cache_read_tokens=coerce_int(payload.get("total_cache_read_tokens"), 0),
+ total_cache_write_tokens=coerce_int(payload.get("total_cache_write_tokens"), 0),
+ total_credit_cost=coerce_float(payload.get("total_credit_cost"), 0.0),
+ cost_provenance=optional_string(payload.get("cost_provenance")) or "unknown",
+ per_model_cost_json=optional_string(payload.get("per_model_cost_json")) or "{}",🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@polylogue/archive/session/models.py` around lines 115 - 122, The new
cost/token fields declared on the SessionProfile dataclass (total_input_tokens,
total_output_tokens, total_cache_read_tokens, total_cache_write_tokens,
total_credit_cost, cost_provenance, per_model_cost_json) are missing from
SessionProfile.to_dict and SessionProfile.from_dict, causing silent loss on
serialization/deserialization; update SessionProfile.to_dict to include those
fields in the returned dict (same key names as the attributes) and update
SessionProfile.from_dict to read those keys from the input dict (use
dict.get(..., <current default>) to preserve existing defaults) so round-trips
retain cost/token data.
| # Mutation operations (mutate-add-tag, mutate-remove-tag, mutate-set-metadata, | ||
| # etc.) are runtime mutations not covered by the scenario coverage graph. | ||
| assert all(name.startswith("mutate-") for name in payload["scenario_coverage"]["uncovered_operations"]) |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial | ⚡ Quick win
all(...) over a potentially empty list is a silent no-op if uncovered_operations becomes empty.
all(pred, []) returns True, so if the scenario coverage graph were ever wired up to cover the mutate-* operations (or if the key goes missing), this assertion passes vacuously and gives no signal.
Consider adding a guard that explicitly asserts the list is non-empty when mutations are expected:
+ assert payload["scenario_coverage"]["uncovered_operations"], (
+ "expected at least the mutate-* operations to remain uncovered"
+ )
assert all(name.startswith("mutate-") for name in payload["scenario_coverage"]["uncovered_operations"])📝 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.
| # Mutation operations (mutate-add-tag, mutate-remove-tag, mutate-set-metadata, | |
| # etc.) are runtime mutations not covered by the scenario coverage graph. | |
| assert all(name.startswith("mutate-") for name in payload["scenario_coverage"]["uncovered_operations"]) | |
| # Mutation operations (mutate-add-tag, mutate-remove-tag, mutate-set-metadata, | |
| # etc.) are runtime mutations not covered by the scenario coverage graph. | |
| assert payload["scenario_coverage"]["uncovered_operations"], ( | |
| "expected at least the mutate-* operations to remain uncovered" | |
| ) | |
| assert all(name.startswith("mutate-") for name in payload["scenario_coverage"]["uncovered_operations"]) |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@tests/unit/devtools/test_artifact_graph.py` around lines 297 - 299, The
current assertion uses all(...) over
payload["scenario_coverage"]["uncovered_operations"], which passes vacuously for
an empty list; update the test to first assert that
payload["scenario_coverage"]["uncovered_operations"] is present and non-empty
when mutations are expected (e.g., assert
payload["scenario_coverage"]["uncovered_operations"]), then assert that every
name starts with "mutate-" using the existing all(...) check so the test fails
if the list is missing or empty as well as if any item does not match.
| # Mutation operations exposed via MCP and CLI write surfaces. | ||
| "mutate-add-tag", | ||
| "mutate-remove-tag", | ||
| "mutate-set-metadata", | ||
| "mutate-delete-metadata", | ||
| "mutate-delete-conversation", | ||
| "mutate-bulk-tag-conversations", |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial | 💤 Low value
Consider adding contract assertions for new mutation operations.
The six new mutation operations are only checked for set membership. Unlike the query/materialization operations below (which assert kind, mutates_state, produces, path_targets), none of those properties are validated for the mutation ops. At minimum, asserting mutates_state is True and kind is OperationKind.MUTATION (or equivalent) would guard against silent contract drift.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@tests/unit/operations/test_specs.py` around lines 43 - 49, The mutation ops
listed ("mutate-add-tag", "mutate-remove-tag", "mutate-set-metadata",
"mutate-delete-metadata", "mutate-delete-conversation",
"mutate-bulk-tag-conversations") are only membership-checked; add contract
assertions in the test (tests/unit/operations/test_specs.py) that each of these
operations has kind == OperationKind.MUTATION and mutates_state is True (and
optionally validate produces/path_targets if relevant) so the test fails on
silent contract drift. Locate the test that iterates over operation specs and,
for each of the six mutation op ids, assert the op_spec.kind equals
OperationKind.MUTATION and op_spec.mutates_state is True.
| # Second pass on the same bundle either skips (if row_graph_hash also | ||
| # matches) or rewrites the same row idempotently. Both are valid; the | ||
| # contract is that the archive is unchanged content-wise. | ||
| assert second.conversations + second.skipped_conversations == 1 | ||
| assert second.messages + second.skipped_messages == 1 |
There was a problem hiding this comment.
Preserve attachment idempotency coverage in this test
This relaxed assertion set no longer checks second-pass attachment accounting, even though the fixture includes one attachment. Please add an aggregate idempotency assertion for attachments as well to keep this test guarding the full bundle contract.
Suggested patch
assert second.conversations + second.skipped_conversations == 1
assert second.messages + second.skipped_messages == 1
+ assert second.attachments + second.skipped_attachments == 1📝 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.
| # Second pass on the same bundle either skips (if row_graph_hash also | |
| # matches) or rewrites the same row idempotently. Both are valid; the | |
| # contract is that the archive is unchanged content-wise. | |
| assert second.conversations + second.skipped_conversations == 1 | |
| assert second.messages + second.skipped_messages == 1 | |
| # Second pass on the same bundle either skips (if row_graph_hash also | |
| # matches) or rewrites the same row idempotently. Both are valid; the | |
| # contract is that the archive is unchanged content-wise. | |
| assert second.conversations + second.skipped_conversations == 1 | |
| assert second.messages + second.skipped_messages == 1 | |
| assert second.attachments + second.skipped_attachments == 1 |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@tests/unit/pipeline/test_prepare.py` around lines 36 - 40, The test relaxes
idempotency checks but forgot attachments: add an aggregate assertion like the
existing ones that verifies second.attachments + second.skipped_attachments == 1
so the second-pass accounting for attachments is covered; update the test around
the other aggregate assertions (referencing the second variable and its
attachments and skipped_attachments properties) to include this check.
| assert est.total_tokens > 0 | ||
| assert est.confidence == "estimated" | ||
| assert est.provenance == "word_count_estimated" | ||
| assert est.provenance == "heuristic_estimated" | ||
|
|
||
|
|
||
| def test_subscription_credit_cost() -> None: | ||
| """Credit cost computation uses per-model rates.""" | ||
| from polylogue.archive.semantic.subscription_pricing import compute_credit_cost | ||
|
|
||
| cost = compute_credit_cost("claude-sonnet-4-6", input_tokens=1000, output_tokens=500) | ||
| assert cost.input_credits > 0 | ||
| assert cost.output_credits > 0 | ||
| assert cost.total_credits > 0 | ||
| assert cost > 0 |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial | ⚡ Quick win
test_subscription_credit_cost over-simplified — single cost > 0 is not specific enough.
The original test verified input_credits, output_credits, and total_credits individually. The replacement assert cost > 0 will pass even if the function returns a raw total that conflates or drops the per-component breakdown. If compute_credit_cost regresses (e.g., always returns a small positive constant), this assertion would not catch it.
Consider also asserting the expected magnitude or structure, e.g.:
cost = compute_credit_cost("claude-sonnet-4-6", input_tokens=1000, output_tokens=500)
- assert cost > 0
+ assert cost > 0
+ # Sanity: 1000 input + 500 output for sonnet-4-6 should be > $0.001
+ assert cost > 0.001, f"suspiciously low cost: {cost}"🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@tests/unit/storage/test_cost_queries.py` around lines 42 - 52, The
test_subscription_credit_cost is too weak with only assert cost > 0; update the
test to assert the per-component credit breakdown returned by
compute_credit_cost rather than just a scalar—call
compute_credit_cost("claude-sonnet-4-6", input_tokens=1000, output_tokens=500)
and assert expected values or ranges for input_credits, output_credits and
total_credits (and/or that total_credits == input_credits + output_credits) so
regressions that drop or conflate components are caught; reference
compute_credit_cost and the test_subscription_credit_cost function when making
the change.
| assert result == [] | ||
| mock_provider._get_connection.assert_not_called() | ||
| # The provider may now open a connection in the embedding-empty branch | ||
| # for an early existence check before bailing out; the contract is | ||
| # that the result is empty, not that no IO is performed. | ||
|
|
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win
Preserve the connection-cleanup contract in the empty-embedding branch
Good relaxation on not requiring zero IO, but the test now drops the “close connections” contract from Line 336 for this path. Please assert that if a connection is opened, it is closed before return.
Suggested test adjustment
else:
assert result == []
# The provider may now open a connection in the embedding-empty branch
# for an early existence check before bailing out; the contract is
# that the result is empty, not that no IO is performed.
+ if mock_provider._get_connection.called:
+ connection.close.assert_called()🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@tests/unit/storage/test_vec.py` around lines 375 - 379, The empty-embedding
test currently only asserts result == [] but must also verify the "close
connections" contract: update the test around the empty-embedding branch to
detect whether a connection was opened (e.g., spy/mocking call to the provider's
connection open method or the connection object created in this test) and assert
that if such an open occurred, the corresponding close/cleanup method (e.g.,
connection.close or provider.close_connection) was called before the function
returned; keep the existing result == [] assertion and add the conditional
assertion that the close call count is >=1 if the open call count is >=1 so the
connection is always closed when opened.
## Summary Addresses all 21 review comments on #959. ## Changes - Schema v12 in-place migration (ALTER TABLE ADD COLUMN for cost/token columns) - Fix outlook cycle-end bug (use `start.month`, not `now.month`) - Make `_as_float` robust against `ValueError`/`TypeError` - Update `SessionProfileDocument` TypedDict with cost fields - `source_name` extraction: use `isinstance(str)` check at all 3 sites - Remove unconditional legacy DB fallback in `ConversationFormatter` - Restore stricter assertions in `test_check.py`, `test_prepare.py`, `test_status.py`, `test_daemon_status.py`, `test_vec.py`, `test_cost_queries.py` - Add `all()` empty-guard in test_artifact_graph.py - Document `--no-*` flags in NixOS module - Use compiled multiline regex for `<file path=` context-dump detection - Add mutation operation contract assertions in `test_specs.py` 17 files changed, +82/-29.
## Summary Post-merge review feedback follow-up for #959. Hardens defensive code, fills in a missing schema upgrade plan, and tightens test assertions where applicable. ## Problem Several review findings surfaced after #959 merged: - Bare str() calls on provider_meta.get("source") could crash on non-string values - _as_float() in outlook.py could crash on non-numeric values - build_v11_to_v12_upgrade_plan was missing — the v12 schema had no in-place upgrade path - core_formatter.py had a fallback to archive_root / "polylogue.db" that masked config issues ## Solution - Defensive source_name extraction in 3 locations (ingest_worker, conversations.py, conversations_writes.py) - try/except in _as_float(); fix month reference in _resolve_cycle - Add build_v11_to_v12_upgrade_plan with cost/token columns for messages and session_profiles - Remove fallback path in core_formatter.py - Compiled regex optimization for file-path line detection - Wire cost fields through SessionProfile serialization (documents, models, profiles) - Tighten test assertions where invariants hold; revert 3 assertions that claimed tighter behavior than code provides (idempotency, FTS readiness model, freshness probe count) ## Verification - devtools verify --quick — all checks passed - pytest on 6 touched test files — 103 passed, 3 corrected assertions now pass
|
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
Restore the local verification baseline to green (format/lint/mypy/render/topology/budgets/manifests) and reconcile partially-implemented closed-scope work. Pytest goes from 346 failures to 0 (5859 passed, 1 pre-existing xfail).
Problem
devtools verify --quickwas red across every gate. 95 mypy errors. 10 topology orphans. 346 test failures. Several closed issues landed scaffolding without reaching product closure. The underlying causes: schema/upsert drift from the #943 cost-attribution work, FTS external-content table incompatibility with SQLite >=3.50, and config-layer rot from multiple refactors.Solution
Schema v12 — messages table gains
input_tokens,output_tokens,cache_read_tokens,cache_write_tokens,model_nameto match the UPSERT SQL already referencing them.FTS fix — Five code paths handled
DELETE FROM messages_ftson external-content FTS5 tables, which raises "database disk image is malformed" when rowids aren't in the index. Replaced with FTS5-safe commands (INSERT...VALUES('delete',...)in triggers,AND rowid IN (SELECT id FROM messages_fts_docsize)guard in repair SQL,'delete-all'in rebuild paths).source_name propagation —
conversation_to_recordandsave_conversation_recordnow extract fromprovider_meta.source. Sync ingest path (_conversation_tuple) extended to 15 elements.Config surface — API-default-on, pruned dead keys, TOML section-key round-trip, embedding cost cap, fixed
polylogue configCLI.Bug fixes found during the pass — daemon facets handler async-correctness, pidfile atexit ordering,
ConversationFormatterdb_path resolution,PlainConsolemarkup handling,compute_session_costimport path, attachment upsert column parity.Verification
Closed-issue matrix with 15 classified entries in the #944 closing comment.
116 files changed, +1345/-1396.
🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
costcommand for subscription usage and quota forecastingpolylogue.tomlwith environment variable and CLI overrides--no-watch,--no-browser-capture,--no-api)--role read|write|admin)Changed
--tailquery mode and tail-overlay JSON provenanceBug Fixes
Documentation