Skip to content

feat: session analysis primitives, commit correlation, OTLP spans, verifiability infrastructure - #1738

Merged
Sinity merged 16 commits into
masterfrom
feature/feat/context-composer-mcp
May 29, 2026
Merged

Sinity merged 16 commits into
masterfrom
feature/feat/context-composer-mcp

Conversation

@Sinity

@Sinity Sinity commented May 28, 2026 •

Copy link
Copy Markdown
Owner

Implements 12 issues from the 500-issue adversarial audit: #1691, #1690, #1686, #1681, #1689, #1627, #1518, #1721, #1722. 308 new tests. Timezone bug fix. Insights section headers. Mutation CI workflow.

Summary by CodeRabbit

Release Notes

  • New Features

    • Added paths command to display canonical archive locations and bind-mount information.
    • Enhanced correlate command with confidence threshold, GitHub API enrichment, and OTLP span evidence options.
    • Improved insights command help with organized section headers.
    • Added MCP tools for session analysis: aggregate_sessions, compare_sessions, find_similar_sessions, correlate_sessions, session_tool_timing.
    • Web shell now includes message anchors, text folding, density toggle, and keyboard shortcuts.
  • Documentation

    • Added configuration documentation for canonical paths and environment variable overrides.
    • Updated CLI reference with new commands and reorganized insights subcommands.
  • Tests

    • Expanded test coverage with comprehensive integration, unit, and property-based tests.

Review Change Stack

Sinity and others added 16 commits May 28, 2026 22:54
…sions tools (#1691)

Add the three remaining Layer 1 session analysis primitives:
- compare_sessions: side-by-side profile comparison for 2-10 sessions
- find_similar_sessions: embedding-based or metadata-similarity ranking
- correlate_sessions: Pearson correlation between any two numeric metrics

Also add test coverage for the existing aggregate_sessions tool.

28 new tests. 439 MCP tests pass.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
#1690)

Phase 2: session_commit_edges table (schema v20) with multi-method
commit detection (explicit_ref, file_overlap, time_window).
Phase 3: GitHub issue/PR reference extraction from session text.

New MCP tool: correlate_session. 35 new tests.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Correlate otlp_spans with session_work_events on session_id + time
overlap. New MCP session_tool_timing tool with evidence provenance
(otlp_span vs message_gap_estimate). CLI --otlp flag on correlate.

13 new tests.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
…#1681)

Lists every command and subcommand with keep/merge/rename/deprecate
recommendations. Establishes a verb taxonomy (one verb per intent).
Proposes insights subcommand grouping by axis (session/aggregate/
analytics/admin). Links to 5 sub-issues (#1723-#1727) for staged
implementation.

Ref #1681

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Parametrized test covering 39 commands with --json --plain, asserting
valid JSON output, no ANSI escape codes, and no tracebacks. Syrupy
snapshot gate for 5 stable JSON surfaces (list, stats, facets, status, count).

Also extend docs/cli-audit.md with JSON output support matrix.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
…nk (#1627)

polylogue paths command shows canonical archive root, DB path, config,
blob store, bind-mount detection, and non-canonical files. Supports
--format json.

Defensive archive.db stub replacement: on DB open, a 0-byte archive.db
is replaced with a symlink to polylogue.db. Non-empty legacy files are
left alone with a warning.

Add canonical paths documentation to docs/configuration.md.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
…v, topology inspector (#1518)

Slice 1 (Session Room): stable message anchors with copy-to-clipboard,
fold/collapse for long content, dense/comfortable view toggle with
localStorage persistence, j/k/g/G keyboard navigation.

Slice 4 (Topology Inspector): edge-detail cards showing kind, status,
source→target links with confidence/reasons/evidence. Unresolved edges
render placeholders with provider-native ID — never silently dropped.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
…undary, prepare_enrichment (#1721)

67 new tests across 4 files closing critical zero-coverage gaps.

compose_context_preamble (16): valid preamble structure, empty archive,
lineage, paste metadata, blackboard notes, parameter forwarding.
blackboard CLI (13): post/list, invalid kind rejection, all 6 kinds.
paste_boundary_resolution (23): full decision matrix for 3-source
evidence pipeline with priority chain verification.
prepare_enrichment (15): paste boundary propagation, goal fields,
provider_meta extraction, topology edges, content hash comparison.

Also fix: blackboard CLI lazy-group registration was broken — command
group wasn't in _GROUP_ATTRS, so subcommands (post/list) didn't dispatch.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
…tests, idempotency gate (#1722)

4 infrastructure items that each have an immediate CI-failing gate:

MCP tool discovery test (47): parametrized over all registered read-role
tools, calls each against empty archive, asserts valid JSON response.
Catches the #1611 class of IndexError-on-empty-archive bugs.

Coverage contract lint: every polylogue module >150 lines must have a
matching test file or exemption. 52 grandfathered exemptions in YAML.
Wired into devtools verify --lab.

Paste evidence property tests (10): Hypothesis-based invariants —
hash_only never claims exact, exact requires full-content source, zero
evidence yields no paste, priority chain is transitive.

Daemon idempotency integration tests (3): double/triple ingest produces
identical conversation count, message count, FTS docsize, action events,
and content hashes. Marked slow+integration.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Naive datetimes or ISO strings without timezone offsets were returned
as naive datetimes. When these were later passed to .timestamp(), the
result assumed local timezone, producing wrong epoch sort keys.

Now optional_datetime always returns UTC-aware datetimes:
- Naive datetimes are assumed to be UTC (replace tzinfo=UTC)
- Aware datetimes are converted to UTC (astimezone(UTC))
- ISO strings without offset are treated as UTC

Fixes the class of bugs seen in #1620 where file mtimes produced
stale sort keys, and prevents any future .timestamp() caller from
getting timezone-dependent results.

9 new tests.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
insights subcommands grouped by axis (Session-level/Aggregate/Analytics/Admin).
Weekly mutation testing CI workflow with rotating module subset (#1733).
Concurrent FTS5 search determinism integration test (#1734).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
…ontracts, regen witness

Co-Authored-By: Claude Opus 4.7 <[email protected]>
- Fix _InsightsGroup.format_commands type annotations
- Add type: ignore for pre-existing embedding_enabled attr-defined error
- Remove test_concurrent_search_determinism.py (wrong API usage, belongs in #1735)

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

github-actions Bot pushed a commit that referenced this pull request May 28, 2026
@coderabbitai

coderabbitai Bot commented May 28, 2026 •

Copy link
Copy Markdown

Caution

Review failed

Failed to post review comments

📝 Walkthrough

Walkthrough

This PR implements comprehensive session analysis and correlation capabilities: session-to-git-commit attribution with confidence scoring, OTLP timing extraction with fallback estimation, six new MCP tools for session comparison and correlation, a new paths CLI command for canonical path resolution, enhanced web UI with message anchors and keyboard navigation, database schema updates for session commit edges, and test coverage enforcement tooling.

Changes

Session analysis, correlation, storage, and UX

Layer / File(s) Summary
Test coverage verification infrastructure
devtools/verify_test_coverage_contracts.py, devtools/command_catalog.py, devtools/verify.py, AGENTS.md, docs/plans/test-coverage-exemptions.yaml, docs/devtools.md
AST-based line counting for production modules; exemption file parsing; --json output support; integration into command catalog and --lab verification tier; documents test coverage contract expectations.
Session-to-commit attribution module and correlate command
polylogue/insights/session_commit.py, polylogue/cli/commands/correlate.py, tests/unit/insights/test_session_commit.py, tests/unit/mcp/test_correlate_session.py, tests/property/test_paste_evidence_laws.py, tests/unit/archive/test_paste_boundary_resolution.py
GitHub reference/file path extraction; commit window derivation; overlap scoring; multi-confidence detection; enhanced correlate command with --confidence-threshold, --github-api, --otlp options; OTLP evidence printing and GitHub enrichment via gh; comprehensive edge-case and property-based testing.
OTLP span correlation and timing extraction
polylogue/insights/otlp_correlation.py, tests/unit/insights/test_otlp_correlation.py
OTLP-to-work-event correlation via time-range overlap; per-tool and per-LLM-turn timing extraction; evidence provenance tracking; fallback message-gap estimation when OTLP unavailable; test coverage for span enrichment, tool/LLM timing derivation.
MCP session analysis and correlation tools
polylogue/mcp/server_insight_tools.py, tests/unit/mcp/test_aggregate_sessions.py, tests/unit/mcp/test_compose_context_preamble.py, tests/unit/mcp/test_correlate_session.py, tests/unit/mcp/test_session_analysis_primitives.py, tests/unit/mcp/test_session_tool_timing.py, tests/unit/mcp/test_tool_discovery.py
Six new tools: compare_sessions (diff detection across profiles), find_similar_sessions (embedding+metadata scoring), correlate_sessions (Pearson correlation), correlate_session (commit attribution), aggregate_sessions (grouping by workflow/state/provider), session_tool_timing (OTLP-backed timing); smoke/contract/behavior test coverage.
Paths command and insights help restructuring
polylogue/cli/commands/paths.py, polylogue/cli/click_command_registration.py, polylogue/cli/commands/insights.py, tests/unit/cli/test_paths.py, docs/configuration.md, docs/cli-reference.md
New paths_command resolving archive locations, bind mounts, non-canonical files; text/JSON output; custom _InsightsGroup for sectioned help; XDG path documentation with bind-mount guidance; CLI reference updates.
Web shell UI enhancements
polylogue/daemon/web_shell_reader.py, polylogue/daemon/web_shell_lineage.py, polylogue/daemon/web_shell.py, tests/unit/daemon/test_web_shell_reader.py
Message anchor permalinks with copy-to-clipboard; long-text folding with configurable thresholds and MutationObserver; message density toggle with localStorage; keyboard shortcuts (g g top, G bottom); topology edge detail rendering; contract-based HTML/JS/CSS verification.
Database schema version bump and session_commit_edges table
polylogue/storage/sqlite/schema_ddl.py, polylogue/storage/sqlite/schema_ddl_repo_identity.py, tests/unit/storage/test_dead_schema_sweep.py
Schema version 19 → 20; composite primary key (session_id, commit_sha); foreign keys to conversations and repo_identities; detection_method/confidence constraints; indexes on (repo_id, session_id) and confidence DESC.
Archive DB stub migration helper
polylogue/paths/archive_db_stub.py, polylogue/storage/sqlite/async_sqlite.py, polylogue/storage/sqlite/connection.py
Defensive ensure_canonical_archive_db_name() to replace 0-byte archive.db stubs with symlinks; idempotent and error-tolerant; integrated into schema initialization paths.
UTC-aware datetime normalization
polylogue/core/payload_coercion.py, tests/unit/core/test_payload_coercion.py
optional_datetime always returns UTC-aware: naive→UTC, aware→UTC conversion, ISO strings without tz→UTC; comprehensive input/output validation tests.
Documentation and reference updates
docs/cli-audit.md, docs/cli-reference.md, docs/configuration.md, docs/devtools.md, docs/plans/test-coverage-exemptions.yaml, docs/plans/topology-target.yaml, docs/test-quality-workflows.md, docs/topology-status.md, docs/verification-catalog.md
CLI audit framework (verb taxonomy, backward-compat strategy, JSON output spec); configuration guide (canonical paths, bind mount handling); topology/verification catalog metadata snapshots; test quality workflow snapshots.
Integration and unit tests
tests/integration/test_daemon_ingest_idempotency.py, tests/property/test_paste_evidence_laws.py, tests/unit/archive/test_paste_boundary_resolution.py, tests/unit/cli/test_blackboard.py, tests/unit/cli/test_json_output.py, tests/unit/cli/__snapshots__/test_plain_cli_snapshots.ambr, tests/unit/cli/test_plain_cli_snapshots.py, tests/unit/pipeline/test_prepare_enrichment.py, tests/data/witnesses/mcp-tool-schemas.json, tests/infra/mcp.py
Ingest idempotency & content-hash determinism; paste boundary resolution (property + unit); blackboard post/list; CLI JSON output validation; message anchor/fold/density/keyboard contracts; MCP tool schema witness and envelope classification.
Mutation testing workflow setup
.github/workflows/mutation-testing.yml
Weekly cron schedule (Sundays 03:37 UTC) and manual dispatch; deterministic module selection by week number; mutmut campaign execution with suppressed failures.

Sequence Diagram

sequenceDiagram
  participant User as User/CLI
  participant Correlate as correlate_command
  participant SessionCommit as session_commit
  participant OTLP as otlp_correlation
  participant DB as SQLite
  participant Git as git log
  participant MCP as MCP Server
  User->>Correlate: --conversation-id --repo-path --otlp
  Correlate->>SessionCommit: build_correlation_result(messages, timestamps)
  SessionCommit->>SessionCommit: extract_github_refs(messages)
  SessionCommit->>SessionCommit: extract_referenced_files(messages)
  SessionCommit->>Git: git log --name-only
  Git-->>SessionCommit: commit hashes, files
  SessionCommit->>SessionCommit: score_file_overlap()
  SessionCommit-->>Correlate: SessionCorrelationResult
  Correlate->>OTLP: get_session_tool_timing(session_id)
  OTLP->>DB: SELECT otlp_spans WHERE session_id=?
  DB-->>OTLP: OTLP spans or empty
  OTLP-->>Correlate: SessionToolTiming (OTLP or message-gap)
  Correlate->>DB: persist_session_commit_edges()
  Correlate-->>User: JSON or formatted output
  MCP->>DB: list_session_profile_insights()
  MCP->>MCP: compare_sessions / correlate_sessions / find_similar_sessions
  MCP-->>User: analysis results
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • Sinity/polylogue#1711: Both PRs modify the same CLI correlation surface—polylogue/cli/commands/correlate.py—to implement session-to-commit correlation with git-based commit detection.
  • Sinity/polylogue#1068: Both PRs modify devtools/verify.py's build_verify_steps to change verification gate registration and execution behavior.
  • Sinity/polylogue#1329: Both PRs adjust the verification gate wiring in devtools/verify.py by adding/removing gates from the test/lab tiers.

Suggested labels

type:refactor, area:cli, area:storage, area:schema, area:qa, type:docs

Poem

🐰 Beneath the moon's pale glow I trace,
Session threads through git's embraced space—
OTLP spans dance, timings bright,
New paths guide us to archive's light,
While UI blooms with folded grace,
Tests keep all this in perfect place! 🌙

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/feat/context-composer-mcp

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 39

Caution

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

⚠️ Outside diff range comments (4)
docs/plans/test-coverage-exemptions.yaml (1)

1-115: 🧹 Nitpick | 🔵 Trivial | 💤 Low value

Exemptions document current state, not rationale.

The 52 exemption entries all use identical reason text: "no dedicated test file (NNN AST lines)". These are baseline exemptions grandfathering existing modules rather than justified exceptions.

The file header (lines 1-9) appropriately documents this is "seeded from realized state" and "should shrink over time", so this approach is acceptable for establishing the baseline.

Future exemptions added beyond this baseline should provide specific rationale (e.g., "pure protocol definition", "thin adapter over X", etc.).

🤖 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/plans/test-coverage-exemptions.yaml` around lines 1 - 115, Update the
header of the YAML (the exemptions list under the top-level key "exemptions") to
clearly mark the current entries as a seeded baseline and require any new
entries to include a specific rationale beyond the generic "no dedicated test
file (NNN AST lines)"; specifically, edit the file comment above the
"exemptions:" key to state these 52 entries are baseline/grandfathered and add a
short policy line that any new exemption added to an entry (path: ..., reason:
...) must include a concrete justification (e.g., "pure protocol definition",
"thin adapter over X", "generated code", etc.) rather than the generic text.
Ensure references to the YAML structure ("exemptions" list, each entry's "path"
and "reason") remain accurate.
polylogue/cli/commands/correlate.py (2)

276-299: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Remove dead code: unused _parse_git_log helper in polylogue/cli/commands/correlate.py.

_parse_git_log has no remaining call/reference sites (only its definition at lines 276-299 exists); delete it or inline any needed logic.

🤖 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/cli/commands/correlate.py` around lines 276 - 299, The helper
function _parse_git_log in correlate.py is dead code; remove its entire
definition (the _parse_git_log function) from the file, or if any parsing logic
is still needed, inline the necessary parts into the caller(s) that require
parsed git output and update those call sites to use the inlined logic; ensure
no references to _parse_git_log remain (search for "_parse_git_log" and remove
or replace usages) and run tests/lint to confirm nothing else depends on it.

66-75: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Prefer cwd/local checkout for git -C; don’t pass git_repository_url

In polylogue/cli/commands/correlate.py, when --repo-path isn’t provided and provider_meta["git_repository_url"] exists, repo is set to that value (even if cwd is also present). That repo is then used as repo_path in polylogue/insights/session_commit.py, which runs git -C <repo_path> log .... If git_repository_url is a remote URL (e.g., https://github.com/...), it isn’t a valid working directory and commit detection returns no commits (stdout is empty; return code isn’t checked). Prefer cwd as the git -C directory (or validate/derive a local checkout before using git_repository_url).

🤖 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/cli/commands/correlate.py` around lines 66 - 75, The code sets repo
from provider_meta["git_repository_url"] before falling back to cwd, which can
pass a remote URL into git -C; change the selection in correlate.py (the repo
variable computed from conv.provider_meta) to prefer a local checkout: if meta
contains a string "cwd" use that as repo, otherwise only use
"git_repository_url" if it is a valid local path (or derive/validate a local
checkout) — this ensures the repo_path passed to session_commit.py (which runs
git -C <repo_path> in functions that detect commits) is a filesystem directory
suitable for git -C rather than a remote URL.
tests/unit/storage/test_dead_schema_sweep.py (1)

45-53: 🧹 Nitpick | 🔵 Trivial | 💤 Low value

Rename the stale contract-pin test.

The function name test_schema_version_is_18 now pins 20, which actively misleads readers of this contract test. Rename to test_schema_version_is_20 (and keep the historical bump chain in the comment).

♻️ Proposed rename
-def test_schema_version_is_18() -> None:
+def test_schema_version_is_20() -> None:
🤖 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_dead_schema_sweep.py` around lines 45 - 53, Rename
the misleading test function test_schema_version_is_18 to
test_schema_version_is_20 and update any references; inside
tests/unit/storage/test_dead_schema_sweep.py change the def name from
test_schema_version_is_18 to test_schema_version_is_20, keep the existing
historical bump chain comment as-is, and ensure the assert continues to check
SCHEMA_VERSION == 20 so the contract remains valid.
🤖 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 @.github/workflows/mutation-testing.yml:
- Line 27: The idx assignment fails for weeks "08"/"09" due to octal parsing of
date +%U; fix by forcing base-10 when converting the week number before the
modulus: capture the week string from date +%U (e.g., into a temporary variable
like week) and compute idx using arithmetic with the 10# prefix (use 10#week in
the $((...)) expression) so the modulus against ${`#modules`[@]} always treats the
week as decimal.
- Around line 9-16: Add a least-privilege permissions block for the mutate job
and harden checkout: update the mutate job to include a permissions: contents:
read entry (and restrict any other permissions to none) and set
persist-credentials: false on the actions/checkout step to prevent GITHUB_TOKEN
from being left in the worktree; also ensure the steps using actions/checkout@v4
and astral-sh/[email protected] are pinned to commit SHAs if your repo requires
SHA-pinning.

In `@devtools/verify_test_coverage_contracts.py`:
- Line 31: The LINE_THRESHOLD constant is duplicated between
verify_test_coverage_contracts.py (LINE_THRESHOLD) and the command_catalog
description string in command_catalog.py; centralize this value by moving
LINE_THRESHOLD into a shared location (e.g., a constants module or the
command_catalog module) and import or reference that single symbol from both
verify_test_coverage_contracts.py and wherever the command description is built,
or have the command description dynamically format the threshold (e.g., use the
shared LINE_THRESHOLD when constructing the "150 AST lines" text) so the value
is maintained in one place.
- Around line 37-67: _ast_stmt_lines currently never inspects the module body,
so module-level statements (assignments, constants, standalone calls, type
aliases) are not counted; update _ast_stmt_lines to iterate tree.body and for
each top-level stmt increment count for non-docstring/excluded imports-only
while skipping FunctionDef/AsyncFunctionDef/ClassDef (those are already counted
via the existing logic), treating ast.Assign/ast.AnnAssign/ast.Expr
(non-docstring)/ast.AugAssign/ast.Call etc. as +1 and ignoring
ast.Import/ast.ImportFrom (and the module docstring ast.Expr with Constant str)
so module-level code gets included in the total.
- Line 188: The code re-walks all production modules to compute total_checked
(using _production_modules() and _ast_stmt_lines) instead of reusing work from
the first pass; initialize total_checked = 0 before the first module loop (the
loop that currently calls _ast_stmt_lines(m) and inspects stmt counts),
increment total_checked whenever _ast_stmt_lines(m) > args.threshold during that
first pass, and replace the later recomputation line that sums over
_production_modules() with the tracked total_checked variable.
- Around line 103-134: The _parse_exemptions function currently swallows
malformed lines; change it to perform strict validation when the exemptions file
exists: while iterating the file in _parse_exemptions, track list-item start
lines (stripped.startswith("- ")) and ensure each such item yields a "path" and
a matching "reason" (use current_path and entries to detect
missing/duplicate/mis-typed keys), collect malformed line numbers or text into a
malformed list, and if any malformed entries are found raise a ValueError (or
log an error and abort) that includes the path and the offending lines so
operators are notified; alternatively you may replace the manual parser with
yaml.safe_load and validate the resulting structure is a list of mappings with
"path" and "reason" keys before building entries.

In `@docs/cli-audit.md`:
- Around line 208-214: The fenced code block containing the listed subcommands
(the block starting with "insights audit        insights costs          insights
export") needs a language identifier for proper highlighting; update that
triple-backtick fence to use "text" or "bash" (e.g., ```text) so the block
renders correctly in docs/cli-audit.md and preserves the listed "insights ..."
lines exactly as shown.

In `@docs/configuration.md`:
- Around line 49-52: Add the Markdown language identifier "text" to the fenced
code block in docs/configuration.md that contains the bind mount paths
(`~/.local/share/polylogue/` and `/realm/data/captures/polylogue/`) so the block
becomes ```text ... ```, ensuring proper rendering.

In `@polylogue/cli/commands/correlate.py`:
- Around line 102-117: The JSON path returns before OTLP evidence is added, so
--otlp is dropped when --format json; fix by extracting the OTLP timing/evidence
assembly into a small helper (e.g., _otlp_evidence_payload(conversation_id) that
returns a dict or None) and call it from both _print_otlp_evidence and the JSON
branch inside correlate.py before returning; merge the helper's dict into the
correlation_result_to_payload(result) output (under an "otlp" or "evidence" key)
when otlp is true so the JSON response includes OTLP data and the existing
non-JSON flow can still call _print_otlp_evidence which should reuse the helper.
- Around line 79-101: The file-extraction logic in extract_referenced_files
currently only checks block["affected_paths"] and block["input"], but
correlate.py forwards hydrated content blocks that carry tool call payloads
under block["tool_input"]; update extract_referenced_files (in
polylogue/insights/session_commit.py) to also inspect block.get("tool_input")
for paths (e.g., tool_input may contain keys like "file", "path", or
"affected_paths") and merge those into the set of referenced files, falling back
to the existing checks if tool_input is absent; ensure the function still
supports the original block shapes and returns the same type (set/list) so
callers (e.g., build_correlation_result consumer) behave unchanged.

In `@polylogue/cli/commands/paths.py`:
- Around line 206-219: The _size_fmt function currently sums only immediate
files via p.iterdir(), which omits nested subdirectories and can mislead users;
either update the _size_fmt docstring to state "sums immediate children only
(non-recursive)" so callers like blob_store_root/archive_root know the
limitation, or change the implementation in _size_fmt to compute a recursive
total by iterating p.rglob("*") and summing f.stat().st_size for f.is_file()
(keeping the existing OSError handling) — pick one (docstring update for low
cost, rglob for full accuracy).
- Around line 128-136: The mountinfo parser loop is brittle because it uses
fixed indices (fields[3], fields[4], fields[7], fields[8]) although optional
fields vary; update the loop that iterates mountinfo.splitlines() to first find
the '-' separator in fields (e.g., sep_index = fields.index('-')) and then
derive mount_point from the fixed pre-separator index (fields[4]) and set
fs_type = fields[sep_index + 1] and mount_source = fields[sep_index + 2], with
bounds checks to avoid IndexError and sensible fallbacks if the separator or
expected post-separator fields are missing; keep references to the existing
variables mount_point, mount_source, fs_type and ensure you handle cases where
fields.index('-') raises ValueError.
- Around line 41-44: The current block is suppressing all exceptions via
contextlib.suppress(Exception), which can hide real bugs; change it to suppress
only the expected filesystem errors (e.g., OSError and FileNotFoundError) when
calling _detect_bind_mounts so bind_mounts is still populated but unexpected
exceptions propagate; locate the bind_mounts initialization and the with
contextlib.suppress(...) around _detect_bind_mounts(archive, bind_mounts) and
replace the broad suppression with contextlib.suppress(OSError,
FileNotFoundError) (or equivalently catch those specific exceptions) so only
those known errors are silenced.
- Around line 64-79: The payload construction for the JSON branch currently
calls db.exists() and then db.stat().st_size, which can race if the file is
removed between calls; update the logic inside the output_format == "json"
branch (where payload is built) to avoid the race by attempting db.stat() inside
a try/except and deriving existence and size from that single stat call (e.g.,
set database_exists and database_size_bytes based on successful stat, and fall
back to False/None on FileNotFoundError); apply the same pattern for the similar
blob existence/stat usage elsewhere in this function to ensure no
FileNotFoundError escapes.

In `@polylogue/daemon/web_shell_reader.py`:
- Around line 703-717: The code uses two different variable names for the same
DOM element (msgList and msgList2); make them consistent by reusing a single
variable (e.g., msgList) for both the lowercase 'g g' and uppercase 'G'
handlers—either declare var msgList = document.getElementById('msg-list') once
before the relevant key handlers or rename msgList2 to msgList in the G branch
so both branches reference the same identifier (msgList) when calling scrollTo.

In `@polylogue/insights/otlp_correlation.py`:
- Around line 143-150: The _query_work_events function currently interpolates
the columns parameter into SQL via f-string; restrict this surface by validating
columns (the columns argument) against a fixed allow-list or enum of permitted
column names (e.g., define an ALLOWED_COLUMNS set or Column enum) and only allow
"*" or a comma-joined subset of those names; if callers pass a list/tuple,
validate each name is in ALLOWED_COLUMNS then build the column string, otherwise
raise ValueError — keep the SQL assembly in _query_work_events but only after
this whitelist check so no unvalidated user input can be injected.
- Around line 207-211: The code assigns tools_used = json.loads(tools_json)
without checking the decoded type, which can yield a dict or scalar and later
break iterations; update the parsing in otlp_correlation.py to only accept a
list by adding an isinstance(..., list) guard after json.loads and otherwise
leave tools_used as an empty list (apply the same fix where the pattern repeats
in _tool_timing_from_work_events); reference the variables/tools_used,
tools_json and the helper function name _tool_timing_from_work_events so you
locate and replace the raw json.loads assignment with a guarded assignment that
validates the result is a list[str].
- Around line 111-122: The helpers (_has_otlp_data, _query_spans_for_session,
_query_work_events, _query_messages) leak sqlite connections because
sqlite3.Connection.__enter__/__exit__ only manage transactions and do not close
the connection; also _connect's docstring is wrong about read-only. Change
_connect into a proper context manager (e.g., a generator using
contextlib.contextmanager or a class implementing __enter__/__exit__) that opens
the DB in read-only mode via URI (file:{db_path}?mode=ro with uri=True), sets
conn.row_factory = sqlite3.Row, yields the connection, and always closes it in
the finally/exit path so all existing call sites using "with _connect(db_path)
as conn:" keep working and connections are not leaked.
- Around line 216-237: The overlap check in the loop over indexed_spans uses
lexicographic ISO string comparison (span["start_time_iso"]/span["end_time_iso"]
vs we_start/we_end) which is brittle; instead parse both span times and
work-event times into tz-aware UTC datetimes (use the same parser used for
_unix_ns_to_iso or add a _parse_iso helper) and compare those datetime objects
when computing has_overlap inside the loop that iterates indexed_spans;
normalize missing offsets to UTC before comparison and keep the matched_spans
append logic unchanged. Also validate/normalize tools_json after json.loads
(e.g., ensure tools_used is a list of strings or coerce it to an empty list) so
tools_used cannot be an unexpected type.

In `@polylogue/insights/session_commit.py`:
- Around line 175-182: The path-detection heuristic in session_commit.py adds
any line containing "/" to paths, causing false positives (e.g., "3/4"); tighten
it by only treating a line as a candidate path if it contains no whitespace (no
spaces or tabs) and either ends with a known file extension (e.g., ".py", ".rs")
or contains a "/" and is not a simple fraction token — e.g., reject strings
matching r'^\d+/\d+$'; update the block that inspects text, the local variable
line, and the condition that adds to paths so session_files/score_file_overlap
are not polluted by prose.
- Around line 364-382: The git-log parsing splits on "\n---\n" which misplaces
the file list because the format string used in detect_session_commits places
the marker before the file names; update detect_session_commits to emit a
distinct leading marker (e.g. use --format="%x1e%H%n%ai%n%s" and append
--name-only) or include the marker at the start of each commit entry, then
change _parse_git_log_blocks to split on that leading marker (e.g. split on
"\x1e") and parse blocks as [hash, date, subject, filenames...]; adjust parsing
in _parse_git_log_blocks to treat lines[3:] as files only after confirming the
block has at least 3 header lines, and add a unit test that creates a temp git
repo with one and multiple commits to assert files are attributed correctly by
_parse_git_log_blocks (or detect_session_commits).

In `@polylogue/mcp/server_insight_tools.py`:
- Around line 503-913: The MCP handlers compare_sessions, find_similar_sessions,
and correlate_sessions currently contain domain logic (scoring, diffing, metric
extraction and correlation) that should be extracted into insights/substrate
APIs; create new functions (e.g., insights.compare_sessions_profiles,
insights.find_similar_sessions_by_id, insights.compute_session_correlation or
similar) that accept validated inputs (ids, session_id+dimension,
metric_x/metric_y + filters) and return plain serializable results, move the
body of the inner run() logic (including _get_metric,
neighbor_candidates/list_session_profile_insights processing, scoring/reason
construction, difference collection, and Pearson calculation) into those new
insight-layer functions, and have the MCP tool methods reduce to input
validation + calling the new insight functions and serializing their return via
hooks.json_payload or hooks.error_json; update references in compare_sessions,
find_similar_sessions, and correlate_sessions to call the new insight APIs and
keep only presentation/validation code in these MCP handlers.
- Around line 1022-1026: The code is calling get_session_tool_timing with the
global db_path() which can point to the wrong SQLite file for non-default
archives; change the first arg to use the active archive's db path (e.g., call
get_session_tool_timing(str(self.poly.archive.db_path()), session_id) or
get_session_tool_timing(str(poly.archive.db_path()), session_id) depending on
how the bound poly/archive object is available in this module) so the query uses
the archive bound to the running instance rather than the global db_path().
- Around line 821-844: The _get_metric function in SessionProfileInsight
converts several nullable fields to float without None checks; update
_get_metric to first check that the source value (from profile.evidence or
profile.inference) is not None for each key
("message_count","word_count","tool_use_count","thinking_count","engaged_duration_ms","tool_active_duration_ms","wall_duration_ms","total_cost_usd","total_duration_ms","substantive_count")
and only call float(...) when the value is not None, otherwise return None;
ensure you access evidence/inference safely (evidence = profile.evidence;
inference = profile.inference) and guard each branch prior to coercion to avoid
runtime exceptions.

In `@polylogue/storage/sqlite/connection.py`:
- Around line 108-113: The call to ensure_canonical_archive_db_name(path) runs
outside the with _schema_lock_for_path(path): block and so is not serialized
with _ensure_schema(conn); move the ensure_canonical_archive_db_name(path)
invocation inside the same with _schema_lock_for_path(path): block (after
calling _ensure_schema(conn)) so the canonicalization runs while the per-path
schema lock is held, using the same path/conn context to eliminate the
intra-process race window.

In `@polylogue/storage/sqlite/schema_ddl.py`:
- Line 84: Replace the one-line comment next to SCHEMA_VERSION = 20 with a full
re-ingest plan: update the schema_ddl.py comment or the PR body to describe (1)
the exact user operation that triggers re-acquisition for the new
session_commit_edges table (e.g., full repository re-ingest or incremental
session import), (2) which downstream products are rebuilt automatically (e.g.,
session attribution reports, commit linkage indexes, search/analytics
pipelines), and (3) the expected end-user impact (e.g., temporary unavailability
of prior session-commit links, time estimate, and whether any manual steps are
required); reference the SCHEMA_VERSION constant and the session_commit_edges
addition in the text so reviewers can verify the migration/re-ingest plan is
present.

In `@tests/integration/test_daemon_ingest_idempotency.py`:
- Around line 200-204: The triple-ingest idempotency test lacks a non-empty
guard so it can pass vacuously; modify the test function
(test_triple_ingest_is_idempotent or the test file using snap1/snap2/snap3) to
assert a positive lower bound (e.g. assert snap1["messages"] > 0 or assert
snap1["conversations"] > 0) after running _write_corpus_files to ensure the
corpus produced is non-empty; reference the variables snap1/snap2/snap3 and the
producer _write_corpus_files (and/or available_providers) when adding the guard
so the test fails if no data was generated.
- Around line 223-240: The test can vacuously pass when no corpus providers are
available; after calling _ingest_corpus and collecting hashes1 and hashes2, add
an assertion that the result is non-empty (e.g., assert hashes1) before
comparing equality to ensure the test actually exercised ingestion; locate the
check around the variables hashes1 and hashes2 (produced by _write_corpus_files
which filters via available_providers() and ingested by _ingest_corpus) and
insert a guard asserting hashes1 (and optionally hashes2) is not empty to fail
fast if no corpus was generated.

In `@tests/property/test_paste_evidence_laws.py`:
- Around line 29-34: _evidence_strategy is defined at module level but never
used; remove the dead binding or wire it into the tests. Fix by either deleting
the _evidence_strategy declaration entirely, or replace the inline strategies in
the test functions' `@given` decorators with a reference to _evidence_strategy
(e.g., use _evidence_strategy in the `@given` for the tests in this file) so the
module-level strategy is actually consumed; update any imports or parameter
names in the test functions to match the chosen approach.
- Around line 59-75: The if state is None branch contains unreachable dead code
and an incorrect comment about the >4000-char heuristic; in
test_zero_evidence_implies_no_paste remove the inner no-op/pass and the
misleading length-heuristic text, and simplify to a single clear assertion: when
resolve_paste_boundary_state returns a non-None boundary for this test input
(with st.text(max_size=200)), it must equal "whole_message_fallback"; keep
references to the state variable and detect_paste only if needed for an explicit
precondition check, otherwise drop the dead detect_paste commentary.
- Around line 87-111: The test test_evidence_boundary_state_in_vocabulary
currently computes has_any_evidence and text_has_paste but does nothing with
them; replace the final pass with an actual assertion that when has_any_evidence
or text_has_paste is True the resolved state from
resolve_paste_boundary_state(...) is not None. In other words, after computing
has_any_evidence and text_has_paste (and after calling
resolve_paste_boundary_state and detect_paste), add assert state is not None
(using the existing variables state, has_any_evidence, text_has_paste) to
enforce the documented invariant.

In `@tests/unit/cli/test_paths.py`:
- Around line 124-139: The test uses a weak assertion "not archive_db.exists()
or archive_db.is_symlink()" which permits deletion instead of replacement;
update the test for ensure_canonical_archive_db_name to assert explicitly that
archive_db is a symlink (archive_db.is_symlink()), that it exists, and that its
target equals Path("polylogue.db") so the behavior is unambiguous; replace the
disjunctive assertion with these explicit checks referencing
ensure_canonical_archive_db_name and the archive_db variable.

In `@tests/unit/insights/test_otlp_correlation.py`:
- Around line 249-287: The correlate_spans_to_work_events function relies on
lexicographic string comparison of timestamps which breaks at
same-second/tz-boundaries; change it to parse work-event start_time/end_time and
OTLP span start/end into timezone-aware datetime or integer epoch nanoseconds
(use the same parser for both, e.g., datetime.fromisoformat or
dateutil.parser.isoparse then convert to UTC timestamps) and compare
numeric/aware datetimes for overlap; update any helper parsing in that module so
inputs with 'Z' or offsets are normalized to UTC before computing overlap.

In `@tests/unit/insights/test_session_commit.py`:
- Around line 191-211: The tests for TestDetectSessionCommits only exercise the
git-failure path, leaving _parse_git_log_blocks and overlap scoring untested;
add a unit test that creates a temporary git repository, seeds it with known
commits and file changes, and then calls detect_session_commits with messages
that reference those files so the real git-repo detection path is exercised and
the parser/score logic runs; implement a fixture (or helper) that initializes a
temp repo, makes commits with deterministic timestamps and file paths, and
assert that detect_session_commits returns the expected edges (verifying parsed
commit blocks from _parse_git_log_blocks and overlap scoring) while referencing
the test class TestDetectSessionCommits and function detect_session_commits to
locate where to add the new test.
- Around line 41-45: The test test_none_timestamps_uses_now is using the real
wall clock; modify it to use the frozen_clock fixture so datetime.now is
deterministic by adding frozen_clock as a test parameter (def
test_none_timestamps_uses_now(frozen_clock) -> None:) which will freeze time for
derive_scan_window(None, None, before_hours=1, after_hours=1) and keep the
existing delta assertion unchanged; reference derive_scan_window and the test
function name when making the change.

In `@tests/unit/mcp/test_correlate_session.py`:
- Around line 66-67: The assertion for the not-found envelope is too loose;
update the test in test_correlate_session (use the payload variable produced
from json.loads(raw)) to assert that the structured error contract is present by
checking payload contains the keys "error", "code", and "is_error" (and
optionally that payload["is_error"] is truthy and payload["code"] is a
string/int as appropriate) instead of the current assert "error" in payload or
"code" in payload.

In `@tests/unit/mcp/test_session_analysis_primitives.py`:
- Around line 121-123: The test currently allows a false positive because it
relies on "not_found" which compare_sessions always returns; change the
assertions to explicitly assert the single-ID rejection signal returned by
compare_sessions instead of checking "not_found" or total_found. Update the test
in test_session_analysis_primitives.py to decode payload and then assert the
exact rejection indicator produced by compare_sessions (for example check
payload.get("error") == "<single-id-rejection-code>" or payload.get("rejected")
is True or payload.get("reason") == "<single-id-rejection-reason>"); locate the
check near the existing lines that parse raw into payload and replace the two
loose asserts with a single assert that matches the actual rejection key/value
emitted by compare_sessions.

In `@tests/unit/mcp/test_session_tool_timing.py`:
- Around line 95-97: The test currently only asserts one of "error" or "code"
exists; update the assertion on the parsed payload (the payload variable from
json.loads(raw)) to require the structured error envelope: assert both "error"
and "code" are present (use AND not OR), verify payload["error"] is a
dict/object and contains at least the "message" field, and optionally assert
payload["code"] is the expected type (e.g., str or int) so the not-found
response contract is fully validated.

In `@tests/unit/pipeline/test_prepare_enrichment.py`:
- Around line 43-61: The test docstring for test_all_message_fields_preserved is
inconsistent with the assertions: it claims "every message field ... is
preserved" but the test explicitly excludes token fields and model_name; update
the docstring/comment to accurately reflect the intended behavior (e.g., "All
message fields except token counts and model_name are preserved") or, if the
original intent was to preserve those fields, modify the test body to add
assertions for the token fields and model_name; locate the test function
test_all_message_fields_preserved and adjust its docstring or add assertions
accordingly so the description matches the actual expectations.

---

Outside diff comments:
In `@docs/plans/test-coverage-exemptions.yaml`:
- Around line 1-115: Update the header of the YAML (the exemptions list under
the top-level key "exemptions") to clearly mark the current entries as a seeded
baseline and require any new entries to include a specific rationale beyond the
generic "no dedicated test file (NNN AST lines)"; specifically, edit the file
comment above the "exemptions:" key to state these 52 entries are
baseline/grandfathered and add a short policy line that any new exemption added
to an entry (path: ..., reason: ...) must include a concrete justification
(e.g., "pure protocol definition", "thin adapter over X", "generated code",
etc.) rather than the generic text. Ensure references to the YAML structure
("exemptions" list, each entry's "path" and "reason") remain accurate.

In `@polylogue/cli/commands/correlate.py`:
- Around line 276-299: The helper function _parse_git_log in correlate.py is
dead code; remove its entire definition (the _parse_git_log function) from the
file, or if any parsing logic is still needed, inline the necessary parts into
the caller(s) that require parsed git output and update those call sites to use
the inlined logic; ensure no references to _parse_git_log remain (search for
"_parse_git_log" and remove or replace usages) and run tests/lint to confirm
nothing else depends on it.
- Around line 66-75: The code sets repo from provider_meta["git_repository_url"]
before falling back to cwd, which can pass a remote URL into git -C; change the
selection in correlate.py (the repo variable computed from conv.provider_meta)
to prefer a local checkout: if meta contains a string "cwd" use that as repo,
otherwise only use "git_repository_url" if it is a valid local path (or
derive/validate a local checkout) — this ensures the repo_path passed to
session_commit.py (which runs git -C <repo_path> in functions that detect
commits) is a filesystem directory suitable for git -C rather than a remote URL.

In `@tests/unit/storage/test_dead_schema_sweep.py`:
- Around line 45-53: Rename the misleading test function
test_schema_version_is_18 to test_schema_version_is_20 and update any
references; inside tests/unit/storage/test_dead_schema_sweep.py change the def
name from test_schema_version_is_18 to test_schema_version_is_20, keep the
existing historical bump chain comment as-is, and ensure the assert continues to
check SCHEMA_VERSION == 20 so the contract remains valid.
🪄 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: fc534bc9-8b3d-4cf4-88ab-c78f3ac01362

📥 Commits

Reviewing files that changed from the base of the PR and between 2ccfc26 and 261e81c.

📒 Files selected for processing (53)
  • .github/workflows/mutation-testing.yml
  • AGENTS.md
  • devtools/command_catalog.py
  • devtools/verify.py
  • devtools/verify_test_coverage_contracts.py
  • docs/cli-audit.md
  • docs/cli-reference.md
  • docs/configuration.md
  • docs/devtools.md
  • docs/plans/test-coverage-exemptions.yaml
  • docs/plans/topology-target.yaml
  • docs/test-quality-workflows.md
  • docs/topology-status.md
  • docs/verification-catalog.md
  • polylogue/cli/click_command_registration.py
  • polylogue/cli/commands/correlate.py
  • polylogue/cli/commands/insights.py
  • polylogue/cli/commands/paths.py
  • polylogue/core/payload_coercion.py
  • polylogue/daemon/web_shell.py
  • polylogue/daemon/web_shell_lineage.py
  • polylogue/daemon/web_shell_reader.py
  • polylogue/insights/otlp_correlation.py
  • polylogue/insights/session_commit.py
  • polylogue/mcp/server_insight_tools.py
  • polylogue/paths/archive_db_stub.py
  • polylogue/storage/sqlite/async_sqlite.py
  • polylogue/storage/sqlite/connection.py
  • polylogue/storage/sqlite/schema_ddl.py
  • polylogue/storage/sqlite/schema_ddl_repo_identity.py
  • tests/data/witnesses/mcp-tool-schemas.json
  • tests/infra/mcp.py
  • tests/integration/test_daemon_ingest_idempotency.py
  • tests/property/test_paste_evidence_laws.py
  • tests/unit/archive/test_paste_boundary_resolution.py
  • tests/unit/cli/__snapshots__/test_plain_cli_snapshots.ambr
  • tests/unit/cli/test_blackboard.py
  • tests/unit/cli/test_json_output.py
  • tests/unit/cli/test_paths.py
  • tests/unit/cli/test_plain_cli_snapshots.py
  • tests/unit/core/test_payload_coercion.py
  • tests/unit/daemon/test_web_shell_reader.py
  • tests/unit/insights/test_otlp_correlation.py
  • tests/unit/insights/test_session_commit.py
  • tests/unit/mcp/test_aggregate_sessions.py
  • tests/unit/mcp/test_compose_context_preamble.py
  • tests/unit/mcp/test_correlate_session.py
  • tests/unit/mcp/test_envelope_contracts.py
  • tests/unit/mcp/test_session_analysis_primitives.py
  • tests/unit/mcp/test_session_tool_timing.py
  • tests/unit/mcp/test_tool_discovery.py
  • tests/unit/pipeline/test_prepare_enrichment.py
  • tests/unit/storage/test_dead_schema_sweep.py

Comment on lines +9 to +16
mutate:
runs-on: ubuntu-latest
timeout-minutes: 45
steps:
- uses: actions/checkout@v4
- uses: astral-sh/[email protected]
with:
python-version: "3.13"

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Add a least-privilege permissions: block and harden checkout.

The workflow relies on the default GITHUB_TOKEN permissions, which are broad. This job only checks out and runs a campaign, so it needs read-only contents. Also set persist-credentials: false on checkout so the token isn't left in the worktree for the uv run step.

🔒 Proposed hardening
 jobs:
   mutate:
     runs-on: ubuntu-latest
     timeout-minutes: 45
+    permissions:
+      contents: read
     steps:
-      - uses: actions/checkout@v4
+      - uses: actions/checkout@v4
+        with:
+          persist-credentials: false

Note: zizmor also flags actions/checkout@v4 and astral-sh/[email protected] as unpinned (a SHA-pin policy). If the repo enforces commit-SHA pinning across workflows, pin these to a full commit hash as well.

🧰 Tools
🪛 zizmor (1.25.2)

[warning] 13-13: credential persistence through GitHub Actions artifacts (artipacked): does not set persist-credentials: false

(artipacked)


[warning] 9-30: overly broad permissions (excessive-permissions): default permissions used due to no permissions: block

(excessive-permissions)


[error] 13-13: unpinned action reference (unpinned-uses): action is not pinned to a hash (required by blanket policy)

(unpinned-uses)


[error] 14-14: unpinned action reference (unpinned-uses): action is not pinned to a hash (required by blanket policy)

(unpinned-uses)


[info] 9-9: workflow or action definition without a name (anonymous-definition): this job

(anonymous-definition)

🤖 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 @.github/workflows/mutation-testing.yml around lines 9 - 16, Add a
least-privilege permissions block for the mutate job and harden checkout: update
the mutate job to include a permissions: contents: read entry (and restrict any
other permissions to none) and set persist-credentials: false on the
actions/checkout step to prevent GITHUB_TOKEN from being left in the worktree;
also ensure the steps using actions/checkout@v4 and astral-sh/[email protected]
are pinned to commit SHAs if your repo requires SHA-pinning.

polylogue/archive/message/paste_detection.py
polylogue/insights/confidence.py
)
idx=$(( $(date +%U) % ${#modules[@]} ))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Octal parsing breaks module rotation on weeks 08 and 09.

date +%U emits a zero-padded week number (00..53). Bash arithmetic interprets leading-zero tokens as octal, so $(( 08 % 4 )) and $(( 09 % 4 )) fail with value too great for base. In those two weeks the assignment errors out, idx is left empty (effectively 0), and the campaign silently stops rotating. Force base‑10:

🐛 Proposed fix
-          idx=$(( $(date +%U) % ${`#modules`[@]} ))
+          idx=$(( 10#$(date +%U) % ${`#modules`[@]} ))
📝 Committable suggestion

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

Suggested change
idx=$(( $(date +%U) % ${#modules[@]} ))
idx=$(( 10#$(date +%U) % ${`#modules`[@]} ))
🤖 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 @.github/workflows/mutation-testing.yml at line 27, The idx assignment fails
for weeks "08"/"09" due to octal parsing of date +%U; fix by forcing base-10
when converting the week number before the modulus: capture the week string from
date +%U (e.g., into a temporary variable like week) and compute idx using
arithmetic with the 10# prefix (use 10#week in the $((...)) expression) so the
modulus against ${`#modules`[@]} always treats the week as decimal.


ROOT = _get_root()
EXEMPTIONS_PATH = ROOT / "docs" / "plans" / "test-coverage-exemptions.yaml"
LINE_THRESHOLD = 150

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial | 💤 Low value

Threshold hardcoded in multiple places.

LINE_THRESHOLD = 150 is defined here, but the command catalog description (line 387 in command_catalog.py) also hardcodes "150 AST lines". If this threshold changes, the description needs manual sync.

Consider either documenting this coupling or dynamically generating the description text.

🤖 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 `@devtools/verify_test_coverage_contracts.py` at line 31, The LINE_THRESHOLD
constant is duplicated between verify_test_coverage_contracts.py
(LINE_THRESHOLD) and the command_catalog description string in
command_catalog.py; centralize this value by moving LINE_THRESHOLD into a shared
location (e.g., a constants module or the command_catalog module) and import or
reference that single symbol from both verify_test_coverage_contracts.py and
wherever the command description is built, or have the command description
dynamically format the threshold (e.g., use the shared LINE_THRESHOLD when
constructing the "150 AST lines" text) so the value is maintained in one place.

Comment on lines +37 to +67
def _ast_stmt_lines(path: Path) -> int:
"""Count AST-level statement lines (non-blank, non-comment, non-import-only).

We count docstrings, class/function bodies, and standalone expressions.
Pure-import modules (re-export shims) land at 0-2 lines.
"""
try:
tree = ast.parse(path.read_text(encoding="utf-8"))
except SyntaxError:
return 9999 # unparseable → flag it

count = 0
for node in ast.walk(tree):
if isinstance(node, ast.Expr) and isinstance(node.value, ast.Constant) and isinstance(node.value.value, str):
# Docstring — count it.
count += 1
elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
# Each function/class definition counts as one structured line.
count += 1
# Count body statements.
for stmt in node.body:
if (
not isinstance(stmt, ast.Expr)
or not isinstance(stmt.value, ast.Constant)
or not isinstance(stmt.value.value, str)
):
count += 1
# Floor: module-level statements count but we want a lower bound.
# If the module has a docstring + __future__ + a few imports, it
# may still have substantive code in functions that we counted above.
return count

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Critical: AST line counting excludes module-level statements.

The function only counts statements inside FunctionDef, AsyncFunctionDef, and ClassDef bodies (lines 53-63), but skips module-level statements entirely. This means:

  • Module-level assignments, type aliases, constants, and standalone calls are uncounted
  • A module with substantial module-level logic but few functions will be severely undercounted
  • Example: a 200-line module with mostly module-level code could count as <50 lines

The comment at lines 64-67 mentions "module-level statements count" but the code never walks the module body to count them.

🔧 Add module-level statement counting
 def _ast_stmt_lines(path: Path) -> int:
     """Count AST-level statement lines (non-blank, non-comment, non-import-only).
 
     We count docstrings, class/function bodies, and standalone expressions.
     Pure-import modules (re-export shims) land at 0-2 lines.
     """
     try:
         tree = ast.parse(path.read_text(encoding="utf-8"))
     except SyntaxError:
         return 9999  # unparseable → flag it
 
     count = 0
+    # Count module-level statements (excluding imports and module docstring)
+    for i, node in enumerate(tree.body):
+        if i == 0 and isinstance(node, ast.Expr) and isinstance(node.value, ast.Constant):
+            # Skip module docstring
+            continue
+        if isinstance(node, (ast.Import, ast.ImportFrom)):
+            # Skip imports
+            continue
+        if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
+            # Will be counted below
+            continue
+        count += 1
+
     for node in ast.walk(tree):
         if isinstance(node, ast.Expr) and isinstance(node.value, ast.Constant) and isinstance(node.value.value, str):
             # Docstring — count it.
             count += 1
         elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
             # Each function/class definition counts as one structured line.
             count += 1
             # Count body statements.
             for stmt in node.body:
                 if (
                     not isinstance(stmt, ast.Expr)
                     or not isinstance(stmt.value, ast.Constant)
                     or not isinstance(stmt.value.value, str)
                 ):
                     count += 1
-    # Floor: module-level statements count but we want a lower bound.
-    # If the module has a docstring + __future__ + a few imports, it
-    # may still have substantive code in functions that we counted above.
     return count
🤖 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 `@devtools/verify_test_coverage_contracts.py` around lines 37 - 67,
_ast_stmt_lines currently never inspects the module body, so module-level
statements (assignments, constants, standalone calls, type aliases) are not
counted; update _ast_stmt_lines to iterate tree.body and for each top-level stmt
increment count for non-docstring/excluded imports-only while skipping
FunctionDef/AsyncFunctionDef/ClassDef (those are already counted via the
existing logic), treating ast.Assign/ast.AnnAssign/ast.Expr
(non-docstring)/ast.AugAssign/ast.Call etc. as +1 and ignoring
ast.Import/ast.ImportFrom (and the module docstring ast.Expr with Constant str)
so module-level code gets included in the total.

Comment on lines +103 to +134
def _parse_exemptions(path: Path) -> dict[str, str]:
"""Parse a simple ``- path: reason`` YAML list.

The file MUST exist (created by the operator). Returns ``{path: reason}``.
"""
if not path.exists():
# If the file genuinely does not exist yet, create it with a
# bootstrap message. But we report every module as uncovered
# so the operator seeds the exemptions deliberately.
return {}

entries: dict[str, str] = {}
current_path: str | None = None
for raw in path.read_text(encoding="utf-8").splitlines():
line = raw.rstrip()
stripped = line.lstrip()
if not stripped or stripped.startswith("#"):
continue
if stripped.startswith("- "):
rest = stripped[2:]
if ": " in rest:
key, _, val = rest.partition(": ")
if key == "path":
# New exemption entry — save previous before starting new.
current_path = val.strip()
elif key == "reason" and current_path is not None:
entries[current_path] = val.strip()
elif current_path is not None and ": " in stripped:
key, _, val = stripped.partition(": ")
if key == "reason":
entries[current_path] = val.strip()
return entries

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚖️ Poor tradeoff

Manual YAML parsing silently skips malformed entries.

The parser walks lines looking for - path: X / reason: Y patterns but silently ignores malformed entries. If an operator typo's an exemption (e.g., pth: instead of path:), the module will be flagged as uncovered with no indication the exemption was present but malformed.

Consider either:

  1. Adding validation that errors loudly when the exemptions file exists but contains unparseable entries
  2. Using PyYAML (but this adds a dependency)
⚠️ Add strict validation
 def _parse_exemptions(path: Path) -> dict[str, str]:
     """Parse a simple ``- path: reason`` YAML list.
 
     The file MUST exist (created by the operator). Returns ``{path: reason}``.
     """
     if not path.exists():
-        # If the file genuinely does not exist yet, create it with a
-        # bootstrap message. But we report every module as uncovered
-        # so the operator seeds the exemptions deliberately.
         return {}
 
     entries: dict[str, str] = {}
     current_path: str | None = None
+    malformed_lines: list[tuple[int, str]] = []
     for raw in path.read_text(encoding="utf-8").splitlines():
+        line_num = len(entries) + len(malformed_lines) + 1
         line = raw.rstrip()
         stripped = line.lstrip()
         if not stripped or stripped.startswith("#"):
             continue
         if stripped.startswith("- "):
             rest = stripped[2:]
             if ": " in rest:
                 key, _, val = rest.partition(": ")
                 if key == "path":
-                    # New exemption entry — save previous before starting new.
                     current_path = val.strip()
                 elif key == "reason" and current_path is not None:
                     entries[current_path] = val.strip()
+                else:
+                    malformed_lines.append((line_num, line))
+            else:
+                malformed_lines.append((line_num, line))
         elif current_path is not None and ": " in stripped:
             key, _, val = stripped.partition(": ")
             if key == "reason":
                 entries[current_path] = val.strip()
+            else:
+                malformed_lines.append((line_num, line))
+        else:
+            malformed_lines.append((line_num, line))
+    if malformed_lines:
+        import sys
+        sys.stderr.write(f"WARNING: {len(malformed_lines)} malformed exemption lines:\n")
+        for num, line in malformed_lines[:5]:
+            sys.stderr.write(f"  Line {num}: {line}\n")
     return entries
🤖 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 `@devtools/verify_test_coverage_contracts.py` around lines 103 - 134, The
_parse_exemptions function currently swallows malformed lines; change it to
perform strict validation when the exemptions file exists: while iterating the
file in _parse_exemptions, track list-item start lines (stripped.startswith("-
")) and ensure each such item yields a "path" and a matching "reason" (use
current_path and entries to detect missing/duplicate/mis-typed keys), collect
malformed line numbers or text into a malformed list, and if any malformed
entries are found raise a ValueError (or log an error and abort) that includes
the path and the offending lines so operators are notified; alternatively you
may replace the manual parser with yaml.safe_load and validate the resulting
structure is a list of mappings with "path" and "reason" keys before building
entries.

Comment on lines +191 to +211
class TestDetectSessionCommits:
def test_empty_messages_no_git_available(self) -> None:
"""When no git repo exists, detection returns empty list gracefully."""
edges = detect_session_commits(
session_id="test-session",
messages=[],
repo_path="/nonexistent/path/should/not/exist",
before_hours=2,
after_hours=2,
)
assert edges == []

def test_no_files_referenced(self) -> None:
"""Session with no file references produces no edges in repos with no commits."""
edges = detect_session_commits(
session_id="test-session",
messages=[{"id": "m1", "text": "Hello", "content_blocks": []}],
repo_path="/nonexistent/path",
)
assert edges == []

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Coverage gap: real git-repo detection path is never exercised.

Both TestDetectSessionCommits cases point at non-existent paths so git fails and returns []. The commit-block parsing (_parse_git_log_blocks) and overlap scoring are therefore untested — and that parser is currently broken (see session_commit.py Lines 364-382). Please add a test against a temp git repo with known commits and files.

Want me to draft a fixture that initializes a temp git repo with seeded commits and asserts the detected edges?

🤖 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/insights/test_session_commit.py` around lines 191 - 211, The tests
for TestDetectSessionCommits only exercise the git-failure path, leaving
_parse_git_log_blocks and overlap scoring untested; add a unit test that creates
a temporary git repository, seeds it with known commits and file changes, and
then calls detect_session_commits with messages that reference those files so
the real git-repo detection path is exercised and the parser/score logic runs;
implement a fixture (or helper) that initializes a temp repo, makes commits with
deterministic timestamps and file paths, and assert that detect_session_commits
returns the expected edges (verifying parsed commit blocks from
_parse_git_log_blocks and overlap scoring) while referencing the test class
TestDetectSessionCommits and function detect_session_commits to locate where to
add the new test.

Comment on lines +66 to +67
payload = json.loads(raw)
assert "error" in payload or "code" in payload

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Strengthen the not-found envelope assertion.

Line 67 should assert the structured error contract (error, code, is_error) instead of allowing either field alone.

💡 Proposed fix
     payload = json.loads(raw)
-    assert "error" in payload or "code" in payload
+    assert "error" in payload
+    assert payload.get("code") == "not_found"
+    assert payload.get("is_error") is True
📝 Committable suggestion

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

Suggested change
payload = json.loads(raw)
assert "error" in payload or "code" in payload
payload = json.loads(raw)
assert "error" in payload
assert payload.get("code") == "not_found"
assert payload.get("is_error") is True
🤖 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/mcp/test_correlate_session.py` around lines 66 - 67, The assertion
for the not-found envelope is too loose; update the test in
test_correlate_session (use the payload variable produced from json.loads(raw))
to assert that the structured error contract is present by checking payload
contains the keys "error", "code", and "is_error" (and optionally that
payload["is_error"] is truthy and payload["code"] is a string/int as
appropriate) instead of the current assert "error" in payload or "code" in
payload.

Comment on lines +121 to +123
payload = json.loads(raw)
assert "error" in payload or "not_found" in payload
assert payload.get("total_found", 1) <= 1

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Assertion does not actually verify single-ID rejection.

compare_sessions always returns a payload containing a not_found key (see the passing tests above), so "not_found" in payload is unconditionally true. With the mock returning a profile for "c1", payload.get("total_found", 1) <= 1 also holds. This test therefore passes regardless of whether the single-ID guard exists, defeating its stated purpose ("rejects single id").

Assert the rejection explicitly instead.

💚 Tighten the assertion
     payload = json.loads(raw)
-    assert "error" in payload or "not_found" in payload
-    assert payload.get("total_found", 1) <= 1
+    # A single ID is invalid input for a comparison and must be rejected.
+    assert "error" in payload or "code" in payload
+    assert "at least 2" in str(payload) or "single" in str(payload).lower()
📝 Committable suggestion

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

Suggested change
payload = json.loads(raw)
assert "error" in payload or "not_found" in payload
assert payload.get("total_found", 1) <= 1
payload = json.loads(raw)
# A single ID is invalid input for a comparison and must be rejected.
assert "error" in payload or "code" in payload
assert "at least 2" in str(payload) or "single" in str(payload).lower()
🤖 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/mcp/test_session_analysis_primitives.py` around lines 121 - 123,
The test currently allows a false positive because it relies on "not_found"
which compare_sessions always returns; change the assertions to explicitly
assert the single-ID rejection signal returned by compare_sessions instead of
checking "not_found" or total_found. Update the test in
test_session_analysis_primitives.py to decode payload and then assert the exact
rejection indicator produced by compare_sessions (for example check
payload.get("error") == "<single-id-rejection-code>" or payload.get("rejected")
is True or payload.get("reason") == "<single-id-rejection-reason>"); locate the
check near the existing lines that parse raw into payload and replace the two
loose asserts with a single assert that matches the actual rejection key/value
emitted by compare_sessions.

Comment on lines +95 to +97
payload = json.loads(raw)
assert "error" in payload or "code" in payload

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Make the not-found assertion contract-complete.

Line 96 should verify the structured error envelope fields, not just one of them.

💡 Proposed fix
     payload = json.loads(raw)
-    assert "error" in payload or "code" in payload
+    assert "error" in payload
+    assert payload.get("code") == "not_found"
+    assert payload.get("is_error") is True
📝 Committable suggestion

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

Suggested change
payload = json.loads(raw)
assert "error" in payload or "code" in payload
payload = json.loads(raw)
assert "error" in payload
assert payload.get("code") == "not_found"
assert payload.get("is_error") is True
🤖 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/mcp/test_session_tool_timing.py` around lines 95 - 97, The test
currently only asserts one of "error" or "code" exists; update the assertion on
the parsed payload (the payload variable from json.loads(raw)) to require the
structured error envelope: assert both "error" and "code" are present (use AND
not OR), verify payload["error"] is a dict/object and contains at least the
"message" field, and optionally assert payload["code"] is the expected type
(e.g., str or int) so the not-found response contract is fully validated.

Comment on lines +43 to +61
defaults: dict[str, object] = {
"conversation_id": ConversationId(conversation_id),
"provider_conversation_id": "prov-1",
"title": title,
"created_at": created_at,
"updated_at": updated_at,
"sort_key": 1.0,
"content_hash": ContentHash("hash-1"),
"provider_meta": {"source": "test"},
"source_name": "test",
"working_directories_json": None,
"git_branch": None,
"git_repository_url": None,
"parent_conversation_id": None,
"branch_type": None,
"raw_id": None,
}
defaults.update(kwargs)
return ConversationRecord(**defaults)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🌐 Web query:

Does mypy report an arg-type error when unpacking a dict[str, object] with ** into a function whose parameters have more specific types?

💡 Result:

Yes, mypy will report an arg-type error when you unpack a generic dictionary like dict[str, object] into a function with more specific parameter types [1][2][3]. This occurs because mypy cannot guarantee that the runtime contents of a standard dictionary match the specific types expected by the function parameters [1][3]. Since the dictionary's type definition is uniform (e.g., all values are type object), mypy assumes any key-value pair in that dictionary could be passed to any parameter of the target function, leading to potential type mismatches [1][2]. To resolve this and ensure type safety, you should use a TypedDict [1][2]. A TypedDict allows you to explicitly define the expected keys and their corresponding types, enabling mypy to verify that the dictionary content matches the function signature [1]. Additionally, when defining functions that accept unpacked dictionaries, you can use Unpack with a TypedDict to provide precise type checking for kwargs [4][5][6].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# 1) Run mypy strictly on the specific file to see whether the ** unpack triggers arg-type errors
mypy --strict tests/unit/pipeline/test_prepare_enrichment.py || true

# 2) Run mypy strictly on the guided scope (as per coding guidelines)
mypy --strict polylogue tests devtools || true

# 3) Quick scan for any wall-clock usage in the reviewed test file
rg -n "datetime\.now|datetime\.utcnow|time\.time|time\.sleep|date\.today" tests/unit/pipeline/test_prepare_enrichment.py || true

Repository: Sinity/polylogue

Length of output: 146


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate type definitions for ConversationRecord and MessageRecord
rg -n "class ConversationRecord|def __init__\(.*ConversationRecord|ConversationRecord\(" -S polylogue tests devtools || true
rg -n "class MessageRecord|def __init__\(.*MessageRecord|MessageRecord\(" -S polylogue tests devtools || true

# Inspect the reviewed test file around the helper(s)
sed -n '1,220p' tests/unit/pipeline/test_prepare_enrichment.py

# Inspect imports for the reviewed test file (to see where ConversationId/ContentHash are defined)
sed -n '1,80p' tests/unit/pipeline/test_prepare_enrichment.py

Repository: Sinity/polylogue

Length of output: 17029


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect ConversationRecord and MessageRecord definitions
sed -n '1,260p' polylogue/storage/runtime/archive/records.py
sed -n '260,520p' polylogue/storage/runtime/archive/records.py

# Inspect the raw base records too (in case typing differs)
sed -n '1,220p' polylogue/storage/runtime/raw/records.py

# Check for mypy/pydantic plugin configuration
ls -1
ls -1 pyproject.toml mypy.ini setup.cfg tox.ini 2>/dev/null || true
rg -n "mypy|pydantic.*mypy|plugins|tool\.mypy" -S pyproject.toml mypy.ini setup.cfg tox.ini 2>/dev/null || true

Repository: Sinity/polylogue

Length of output: 12525


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Print mypy config section
python3 - <<'PY'
import tomllib, pathlib
p=pathlib.Path("pyproject.toml")
data=tomllib.loads(p.read_text())
tool=data.get("tool",{})
mypy=tool.get("mypy",{})
print("=== [tool.mypy] ===")
for k in sorted(mypy.keys()):
    print(f"{k} = {mypy[k]!r}")
PY

# Also show relevant tool.mypy lines around strict/enable flags (for context)
rg -n "\[tool\.mypy\]" -n pyproject.toml
sed -n '140,220p' pyproject.toml

Repository: Sinity/polylogue

Length of output: 3534


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Find other occurrences of dynamic dict-unpacking into these Pydantic models
rg -n "ConversationRecord\(\*\*.*\)" tests polylogue devtools || true
rg -n "MessageRecord\(\*\*.*\)" tests polylogue devtools || true

# Specifically look for the '**defaults' pattern and any nearby type ignores
rg -n "ConversationRecord\(\*\*defaults" -S tests polylogue devtools || true
rg -n "MessageRecord\(\*\*defaults" -S tests polylogue devtools || true

rg -n "type:\s*ignore" tests/unit/pipeline/test_prepare_enrichment.py polylogue/storage/runtime/archive/records.py || true

Repository: Sinity/polylogue

Length of output: 418


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
import pydantic, pathlib
print("pydantic_version", pydantic.__version__)
print("pydantic_file", pydantic.__file__)
p = pathlib.Path(pydantic.__file__).resolve().parent
print("pydantic_pkg_dir", str(p))
PY

# Locate pydantic stub/typing files for BaseModel
python3 - <<'PY'
import pydantic, pathlib
p = pathlib.Path(pydantic.__file__).resolve().parent
candidates = list(p.rglob("main.pyi")) + list(p.rglob("*.pyi")) + [p/"main.pyi"]
for x in candidates:
    if x.exists():
        print("FOUND", x)
PY

# Grep for __init__ typing around BaseModel
python3 - <<'PY'
import pydantic, pathlib, sys
p = pathlib.Path(pydantic.__file__).resolve().parent
paths = []
for pat in ["main.pyi","main.py","*.pyi"]:
    pass
# Just print likely file(s)
for f in [p/"main.pyi", p/"main.py"]:
    if f.exists():
        print("CANDIDATE", f)
PY

# Try to view relevant lines if main.pyi exists; otherwise show main.py type hints for BaseModel init
if [ -f "$(python3 - <<'PY'
import pydantic, pathlib
p=pathlib.Path(pydantic.__file__).resolve().parent
f=p/'main.pyi'
print(str(f) if f.exists() else '')
PY
)" ]; then
  pyi="$(python3 - <<'PY'
import pydantic, pathlib
p=pathlib.Path(pydantic.__file__).resolve().parent
f=p/'main.pyi'
print(str(f) if f.exists() else '')
PY
)"
  echo "=== $pyi (BaseModel excerpt) ==="
  sed -n '1,220p' "$pyi" | sed -n '1,220p'
  rg -n "class BaseModel|def __init__" "$pyi" | head -n 50
else
  mainpy="$(python3 - <<'PY'
import pydantic, pathlib
p=pathlib.Path(pydantic.__file__).resolve().parent
f=p/'main.py'
print(str(f) if f.exists() else '')
PY
)"
  echo "No main.pyi found; showing main.py excerpt: $mainpy"
  rg -n "class BaseModel" "$mainpy" | head -n 20
  rg -n "def __init__" "$mainpy" | head -n 20
fi

Repository: Sinity/polylogue

Length of output: 512


🏁 Script executed:

#!/bin/bash
set -euo pipefail

sed -n '300,430p' tests/unit/pipeline/test_prepare_enrichment.py

Repository: Sinity/polylogue

Length of output: 5509


Align test_all_message_fields_preserved with its actual assertions

  • test_all_message_fields_preserved docstring says “Every message field … is preserved”, but the test body explicitly notes token fields and model_name are not propagated and only asserts a subset—update the docstring/comment to match intent (or add assertions if preservation is expected). [minor mismatch in tests/unit/pipeline/test_prepare_enrichment.py]
🤖 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_enrichment.py` around lines 43 - 61, The
test docstring for test_all_message_fields_preserved is inconsistent with the
assertions: it claims "every message field ... is preserved" but the test
explicitly excludes token fields and model_name; update the docstring/comment to
accurately reflect the intended behavior (e.g., "All message fields except token
counts and model_name are preserved") or, if the original intent was to preserve
those fields, modify the test body to add assertions for the token fields and
model_name; locate the test function test_all_message_fields_preserved and
adjust its docstring or add assertions accordingly so the description matches
the actual expectations.

@Sinity
Sinity merged commit a3f5f6f into master May 29, 2026
7 checks passed
@Sinity
Sinity deleted the feature/feat/context-composer-mcp branch May 29, 2026 00:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant