Repository navigation
chore: restore mypy --strict CI gate and clean the mechanical tier - #205
Conversation
Re-introduces the type-checking gate that was removed in #174 when it had accumulated 1,764 errors across 232 files. The approach the issue anticipated was "scoped to a subset of clean modules" plus "incrementally expand the scope as modules are cleaned up." Changes: - ``[tool.mypy] exclude`` in ``pyproject.toml`` now lists every currently-dirty file under ``polylogue/*``. 332 clean files remain and pass ``mypy --strict`` with the existing config. The list only shrinks: cleaning a module means removing its entry. - New ``typecheck`` CI job runs ``uv run mypy polylogue/`` on every PR. Any regression — a new type error in a covered file, or a new file that doesn't pass strict — fails CI. - ``mypy`` is pinned to ``>=1.17,<1.18`` in the dev extras so local and CI use the same version the Nix devshell already provides. ``uv.lock`` regenerated to pick up the pin (1.19.1 → 1.17.1). - ``devtools verify`` and ``devtools verify --quick`` both run mypy between ``ruff check`` and ``render-all``. Cold run ~25s, warm run ~1s. Pre-push hook now catches type regressions before they hit CI. - ``CONTRIBUTING.md`` documents the cleanup workflow: pick a file, remove its entry, fix the errors, verify, commit. - CI comment referring to mypy as "tracked debt" removed. Closes #188
📝 WalkthroughWalkthroughRestores mypy type-checking as a CI gate: adds a CI Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In @.github/workflows/ci.yml:
- Around line 60-74: Add a CI guard in the typecheck job to prevent accidental
expansion of the mypy exclude list: implement a new step in the "typecheck" job
(next to the existing uv run mypy polylogue/ step) that runs a small script
which loads [tool.mypy].exclude from pyproject.toml on the current branch and
compares it to the baseline version on main; fail the step if the current
exclude set is not a subset of the baseline (i.e., any new entries were added).
The check should reference the "typecheck" job, the existing mypy run (uv run
mypy polylogue/), and the pyproject.toml [tool.mypy].exclude key so reviewers
can locate where to add the new check.
In `@CONTRIBUTING.md`:
- Around line 209-211: The CONTRIBUTING.md sentence claiming "new files under
polylogue/ are checked by default" is too broad; update it to state that new
polylogue files are checked by default except for any directories explicitly
excluded in pyproject.toml's mypy excludes (for example the providers subtree),
and require that any newly added files landing in non-excluded paths must pass
mypy --strict before merge; reference the CONTRIBUTING.md sentence and
pyproject.toml's mypy exclude configuration when making the wording change.
🪄 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: a110d1db-ee1a-4238-9dae-5105a5d94002
⛔ Files ignored due to path filters (1)
uv.lockis excluded by!**/*.lock,!**/*.lock
📒 Files selected for processing (6)
.github/workflows/ci.ymlCONTRIBUTING.mddevtools/command_catalog.pydevtools/verify.pydocs/devtools.mdpyproject.toml
| typecheck: | ||
| # Strict mypy over the clean subset of polylogue/*. The list of | ||
| # legacy-dirty files is maintained in `pyproject.toml` under | ||
| # `[tool.mypy] exclude` — shrinking that list is the mechanism for | ||
| # widening coverage over time (issue #188). | ||
| timeout-minutes: 10 | ||
| runs-on: ubuntu-latest | ||
| steps: | ||
| - uses: actions/checkout@v6 | ||
| - uses: astral-sh/[email protected] | ||
| with: | ||
| python-version: "3.13" | ||
| - run: uv sync --extra dev --frozen | ||
| - run: uv run mypy polylogue/ | ||
|
|
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Consider enforcing “exclude list only shrinks” directly in CI.
The new job restores typecheck gating, but the shrink-only debt policy is still manual. Adding a guard step would prevent future bypass by expanding [tool.mypy].exclude.
Suggested CI hardening
typecheck:
@@
steps:
- uses: actions/checkout@v6
- uses: astral-sh/[email protected]
with:
python-version: "3.13"
- run: uv sync --extra dev --frozen
+ - name: Ensure mypy exclude list does not grow
+ run: |
+ git fetch origin master --depth=1
+ python - <<'PY'
+ import subprocess, tomllib
+ from pathlib import Path
+
+ base_toml = subprocess.check_output(
+ ["git", "show", "origin/master:pyproject.toml"], text=True
+ )
+ base_exclude = set(tomllib.loads(base_toml)["tool"]["mypy"].get("exclude", []))
+
+ head_toml = Path("pyproject.toml").read_text(encoding="utf-8")
+ head_exclude = set(tomllib.loads(head_toml)["tool"]["mypy"].get("exclude", []))
+
+ added = sorted(head_exclude - base_exclude)
+ if added:
+ print("New [tool.mypy].exclude entries are not allowed:")
+ print("\\n".join(added))
+ raise SystemExit(1)
+ PY
- run: uv run mypy polylogue/🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In @.github/workflows/ci.yml around lines 60 - 74, Add a CI guard in the
typecheck job to prevent accidental expansion of the mypy exclude list:
implement a new step in the "typecheck" job (next to the existing uv run mypy
polylogue/ step) that runs a small script which loads [tool.mypy].exclude from
pyproject.toml on the current branch and compares it to the baseline version on
main; fail the step if the current exclude set is not a subset of the baseline
(i.e., any new entries were added). The check should reference the "typecheck"
job, the existing mypy run (uv run mypy polylogue/), and the pyproject.toml
[tool.mypy].exclude key so reviewers can locate where to add the new check.
Expand #205's gate coverage by fixing the purely-mechanical type errors (annotations, generic parameters, return types) in the files where no design-level issues were lurking. Exclude list shrinks from 232 to 179 entries; gate now covers 385 files (up from 332). Errors fixed are of these kinds: - ``no-untyped-def`` — add argument and return type annotations - ``type-arg`` — add generic parameters (``dict`` → ``dict[str, Any]``) - ``no-any-return`` — cast returns to their declared types - ``var-annotated`` — add explicit variable annotation - ``unused-ignore`` — remove a stale ``# type: ignore`` Six files from the original mechanical-only set remain excluded because their annotation surfaced real issues that belong in focused PRs: - ``polylogue/lib/filters.py`` — ``list`` method name collides with the builtin in type annotations - ``polylogue/schemas/operator_annotations.py`` — ``object``-typed attribute access; actual design debt - ``polylogue/schemas/synthetic/build_records.py``, ``build_wire_formats.py`` — ``object`` attribute-set patterns that need a proper dict typing - ``polylogue/storage/repository_write_conversations.py``, ``repository_write_metadata.py`` — annotating ``backend: SQLiteBackend`` cascades into ``no-untyped-call`` for transaction/connection; blocked by the async-backend cleanup in #190 These six are stable in the exclude list until their paired cleanup lands. No runtime behavior change. Only annotations and one ``str()`` cast on returns where the source function's true type was ``Any``. Ref #188
There was a problem hiding this comment.
Actionable comments posted: 14
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
polylogue/schemas/synthetic/build_batch.py (1)
17-23: 🧹 Nitpick | 🔵 TrivialReplace broad
Anyreceiver typing with a narrow protocol.Line 18, Line 57, and Line 73 use
self: Any, which disables meaningful static checks on the synthetic generation path. Prefer a small Protocol describing only the attributes/methods used here.Proposed typing-only refactor
-from typing import Any +from typing import Any, Protocol + +class _BatchContext(Protocol): + schema: Any + provider: str + package_version: str + element_kind: str + wire_format: Any + _relation_solver: RelationConstraintSolver + _semantic_gen: Any + def _serialize(self, data: Any) -> bytes: ... + def _generate_conversation( + self, n_messages: int, rng: random.Random, *, theme: ConversationTheme | None = None + ) -> Any: ... def generate_batch( - self: Any, + self: _BatchContext, @@ def _generate_conversation( - self: Any, + self: _BatchContext, @@ -def _role_cycle(self: Any) -> list[str]: +def _role_cycle(self: _BatchContext) -> list[str]:Also applies to: 56-63, 73-73
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@polylogue/schemas/synthetic/build_batch.py` around lines 17 - 23, The use of self: Any in generate_batch (and the other methods at the same spots) disables static checking; define a small typing.Protocol (e.g., SyntheticGeneratorProtocol) that declares only the attributes/methods this code uses (for example the random/seed access, any helper methods, or configuration fields referenced in generate_batch) and replace self: Any with self: SyntheticGeneratorProtocol in generate_batch and the other affected method signatures so mypy/IDE can validate usage without changing runtime behavior.polylogue/sources/drive_auth.py (1)
120-125:⚠️ Potential issue | 🟡 MinorReturn type annotation should be
CachedCredentialStateinstead ofAny.The
load_cached_credentialshelper function has a concrete return type ofCachedCredentialState. Keeping the method's return type asAnymasks type errors on attributes accessed from this return value downstream. Update the return type annotation and importCachedCredentialStatefrom.drive_types.Typing fix
-from .drive_types import SCOPES, DriveAuthError +from .drive_types import SCOPES, CachedCredentialState, DriveAuthError @@ - def _load_cached_credentials(self, credentials_cls: Any, token_path: Path) -> Any: + def _load_cached_credentials(self, credentials_cls: Any, token_path: Path) -> CachedCredentialState:🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@polylogue/sources/drive_auth.py` around lines 120 - 125, The method _load_cached_credentials currently annotates its return as Any which hides downstream type errors; change its return type to CachedCredentialState and add an import for CachedCredentialState from .drive_types, then update the signature def _load_cached_credentials(self, credentials_cls: Any, token_path: Path) -> CachedCredentialState so callers get the correct concrete type from load_cached_credentials.polylogue/showcase/workspace.py (1)
204-210:⚠️ Potential issue | 🟡 MinorUse
RunResultinstead of-> objectfor workspace seeding helpers.These four public functions return the result of
run_coroutine_sync(run_sources(...)), which isRunResult, notobject. Using the concrete type enables type-safe consumption by callers. ImportRunResultfrompolylogue.storage.state_viewsand update return type annotations for:
seed_workspace_from_specs(line 210)seed_workspace_from_scenarios(line 230)seed_workspace_from_corpus_request(line 249)seed_workspace_from_corpus_options(line 272)Also applies to
run_pipeline_for_fixture_workspaceandrun_pipeline_for_configured_sourceswhich have the same issue.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@polylogue/showcase/workspace.py` around lines 204 - 210, Update the return type annotations from "object" to the concrete RunResult for the workspace seeding and pipeline helper functions; import RunResult from polylogue.storage.state_views and change the return annotations on seed_workspace_from_specs, seed_workspace_from_scenarios, seed_workspace_from_corpus_request, seed_workspace_from_corpus_options as well as run_pipeline_for_fixture_workspace and run_pipeline_for_configured_sources so they accurately reflect that they return the result of run_coroutine_sync(run_sources(...)) which is a RunResult.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@polylogue/cli/qa_capture.py`:
- Around line 5-8: Replace the loose Any types in run_vhs_capture with concrete
types: use the existing ShowcaseResult dataclass for the showcase_result
parameter (it provides .output_dir and .results) and define a small Protocol
(e.g., EnvWithUI or UIEnv) for env that exposes ui.console.print(...) so the
type checker knows env.ui.console.print exists; import typing.Protocol and
annotate the function signature as run_vhs_capture(env: EnvWithUI,
showcase_result: ShowcaseResult, json_output: bool) and update imports
accordingly.
In `@polylogue/cli/qa_snapshot.py`:
- Line 10: Replace the overly broad env: Any typing by declaring a minimal
Protocol that captures the attributes you actually use (e.g., a Console protocol
with a print method and a UI protocol that exposes a console attribute), import
Protocol from typing, and update the env parameter annotations where used (the
three occurrences in this file) to that Protocol; ensure the new Protocol name
is referenced in function signatures that currently accept env so static
checkers can verify usages like env.ui.console.print.
In `@polylogue/lib/semantic_facts.py`:
- Line 115: The annotation for the variable `timestamps` is too broad
(list[Any]); change it to a more specific datetime type to reflect actual usage:
declare `timestamps` as list[Optional[datetime.datetime]] (or
list[Optional[datetime]] if you import datetime.datetime as datetime) to match
values coming from `message_fact.timestamp` (which can be None) and then after
filtering Nones you can treat the collection as list[datetime.datetime] for
min/max and .total_seconds() operations; also ensure `datetime` is imported at
the top of the module and update any related type hints accordingly.
- Line 33: Replace the use of Any in the seven builder functions with the
concrete domain types: change the projection parameter in
build_projection_semantic_facts to ConversationProjection (import from
polylogue.lib.projections), change message parameters to Message (import from
polylogue.lib.message_models), and change conversation/summary parameters to
Conversation and ConversationSummary (import both from
polylogue.lib.conversation_models); update the function signatures and imports
accordingly so each builder (including build_projection_semantic_facts) uses the
specific types for full static checking and IDE autocomplete.
In `@polylogue/rendering/renderers/html_messages.py`:
- Around line 6-7: Update the type annotation for the render_html parameter in
polylogue/rendering/renderers/html_messages.py from Any to Callable[[str], str]:
import Callable from typing (add to the existing TYPE_CHECKING import) and
change the render_html parameter type in the functions referenced (the two
places around lines 56 and 82 where render_html is typed as Any) to
Callable[[str], str] so it matches build_rendered_message_payload’s expected
callable signature and prevents invalid callables from passing static type
checks.
In `@polylogue/schemas/generation_workflow.py`:
- Line 38: The public functions generate_provider_schema and
generate_all_schemas currently use a return type of Any which disables type
checking; change the annotations so generate_provider_schema -> GenerationResult
and generate_all_schemas -> list[GenerationResult], and ensure the
GenerationResult type is imported or in scope (so the functions return types
match the actual .result and list of results these functions return).
In `@polylogue/schemas/sampling_db.py`:
- Line 51: Change the generator return annotations from Any to explicit Iterator
types: for _iter_schema_units_from_db annotate -> Iterator[SchemaUnit]; for
_iter_samples_from_db provide accurate typed overloads or a unioned Iterator to
reflect the conditional yield shapes (e.g. two `@overload` signatures: one
returning Iterator[dict[str, Any]] when with_conv_ids=False and one returning
Iterator[tuple[dict[str, Any], str | None]] when with_conv_ids=True, with the
implementation annotated as -> Iterator[dict[str, Any] | tuple[dict[str, Any],
str | None]]). Import typing names (Iterator, overload, Union if needed) and
ensure the tuple accounts for conversation_id being str | None as in SchemaUnit.
In `@polylogue/schemas/sampling_sessions.py`:
- Line 22: Two generator functions in polylogue/schemas/sampling_sessions.py
currently annotate their return type as Any; change each signature from "-> Any"
to a proper iterator/generator type (e.g., Iterator[YieldType] or
Generator[YieldType, None, None] or Iterable[YieldType]) that matches the
yielded value type, and add the corresponding import
(Iterator/Generator/Iterable) from typing. Locate the two function definitions
(the signatures at the top-level that currently end with "-> Any" around the
areas noted in the diff) and replace Any with the appropriate typing of the
yielded element (use Generator if you need send/return semantics, otherwise
Iterator/Iterable), ensuring imports are added or adjusted.
In `@polylogue/schemas/sampling.py`:
- Line 30: Change the return annotation of the generator function
iter_schema_units from Any to a proper iterator type: annotate it as
Iterator[SchemaUnit]. Import Iterator from typing (or typing.Iterator) and
ensure SchemaUnit is imported or referenced from its module so the signature
reads something like def iter_schema_units(...) -> Iterator[SchemaUnit]:; this
gives callers a correct type contract for the yielded SchemaUnit values.
In `@polylogue/schemas/synthetic/selection.py`:
- Line 21: The schema annotation in selection.py is incorrectly typed as
dict[str, object] but should match registry.get_element_schema() and the module
convention by using dict[str, Any] | None; update the variable/type annotation
(named schema) in selection.py to dict[str, Any] | None, import Any from typing
if missing, and ensure any places using schema remain compatible with dict[str,
Any] (this aligns selection.py with registry.get_element_schema() and the other
synthetic module files).
In `@polylogue/schemas/synthetic/semantic_values.py`:
- Around line 140-144: The code blindly calls str(...) on arbitrary sampled
values (see self.current_role, self.rng.choice(conversational) and
self.rng.choice(values)), producing artifacts like "None" or "{...}"; change the
sampling logic to first filter candidate pools (conversational and values) to
only real strings (e.g., use isinstance(..., str)) and pick from those; if the
filtered list is empty, fall back to a safe default (e.g., self.current_role or
an explicit default) instead of stringifying non-strings, and apply the same fix
at the other occurrence also noted around line 183.
In `@polylogue/site/builder.py`:
- Line 9: Replace the blanket Any annotations at the wrapper boundaries with the
concrete types already available under TYPE_CHECKING: change
iter_conversation_indexes_for_builder(backend: Any, repository: Any) -> Any to
use backend: SQLiteBackend, repository: ConversationRepository, ->
AsyncIterator[ConversationIndex], and change
generate_conversation_page_for_builder(repository: Any) to repository:
ConversationRepository; ensure from __future__ import annotations is present (or
keep it) and import SQLiteBackend, ConversationRepository, ConversationIndex,
and AsyncIterator inside the TYPE_CHECKING block so the names are available as
forward references without runtime imports, leaving function signatures using
those concrete types (symbols: iter_conversation_indexes_for_builder,
generate_conversation_page_for_builder, backend, repository, SQLiteBackend,
ConversationRepository, ConversationIndex, AsyncIterator).
In `@polylogue/sources/drive_auth_support.py`:
- Around line 66-71: Define small typing.Protocols and use them instead of Any:
add a TokenStoreProtocol that exposes load(path: Path) -> Optional[bytes] and
save(path: Path, data: bytes) -> None (or the exact load/save signatures used in
this module) and a CredentialsFactory/Instance Protocol that includes the
classmethod used to construct creds (e.g. from_authorized_user_info/from_json)
and the instance lifecycle members used in this file (properties/methods like
valid, expired, refresh(request), to_json() or to_authorized_user_info()). Then
change the signature of load_cached_credentials to accept token_store:
TokenStoreProtocol and credentials_cls: CredentialsFactoryProtocol and update
any local variables typed as Any (e.g. creds) to the new Protocol types so
static checkers can verify calls to load(), save(), refresh(), valid, expired,
and to_json()/from_*.
In `@polylogue/sources/token_store.py`:
- Line 82: The keyring import in token_store.py is untyped and fails strict
mypy; restore type checking by either adding the import ignore or providing
types: add `# type: ignore[import]` to the `import keyring` line in
token_store.py, or alternatively add `types-keyring` to the project dependencies
so mypy recognizes keyring's stubs (or add this file to mypy's exclude list) —
pick one of these fixes and apply it to the `import keyring` statement to
satisfy strict mypy.
---
Outside diff comments:
In `@polylogue/schemas/synthetic/build_batch.py`:
- Around line 17-23: The use of self: Any in generate_batch (and the other
methods at the same spots) disables static checking; define a small
typing.Protocol (e.g., SyntheticGeneratorProtocol) that declares only the
attributes/methods this code uses (for example the random/seed access, any
helper methods, or configuration fields referenced in generate_batch) and
replace self: Any with self: SyntheticGeneratorProtocol in generate_batch and
the other affected method signatures so mypy/IDE can validate usage without
changing runtime behavior.
In `@polylogue/showcase/workspace.py`:
- Around line 204-210: Update the return type annotations from "object" to the
concrete RunResult for the workspace seeding and pipeline helper functions;
import RunResult from polylogue.storage.state_views and change the return
annotations on seed_workspace_from_specs, seed_workspace_from_scenarios,
seed_workspace_from_corpus_request, seed_workspace_from_corpus_options as well
as run_pipeline_for_fixture_workspace and run_pipeline_for_configured_sources so
they accurately reflect that they return the result of
run_coroutine_sync(run_sources(...)) which is a RunResult.
In `@polylogue/sources/drive_auth.py`:
- Around line 120-125: The method _load_cached_credentials currently annotates
its return as Any which hides downstream type errors; change its return type to
CachedCredentialState and add an import for CachedCredentialState from
.drive_types, then update the signature def _load_cached_credentials(self,
credentials_cls: Any, token_path: Path) -> CachedCredentialState so callers get
the correct concrete type from load_cached_credentials.
🪄 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: 37e199af-f40c-44fd-a0f2-ccb1b4721de7
📒 Files selected for processing (52)
polylogue/cli/check_maintenance.pypolylogue/cli/check_support.pypolylogue/cli/check_validation.pypolylogue/cli/helpers.pypolylogue/cli/qa_capture.pypolylogue/cli/qa_snapshot.pypolylogue/cli/run_display_workflow.pypolylogue/cli/run_watch_workflow.pypolylogue/cli/run_workflow.pypolylogue/cli/schema_command_support.pypolylogue/cli/schema_rendering_explain.pypolylogue/cli/schema_rendering_results.pypolylogue/lib/raw_payload_sampling_buckets.pypolylogue/lib/semantic_facts.pypolylogue/mcp/__init__.pypolylogue/mcp/server_support.pypolylogue/pipeline/prepare.pypolylogue/pipeline/run_state.pypolylogue/rendering/renderers/html_highlighting.pypolylogue/rendering/renderers/html_messages.pypolylogue/rendering/renderers/html_template.pypolylogue/schemas/field_stats_models.pypolylogue/schemas/generation_schema_builder.pypolylogue/schemas/generation_semantic_relations.pypolylogue/schemas/generation_support.pypolylogue/schemas/generation_workflow.pypolylogue/schemas/operator_workflow.pypolylogue/schemas/privacy_config.pypolylogue/schemas/sampling.pypolylogue/schemas/sampling_db.pypolylogue/schemas/sampling_sessions.pypolylogue/schemas/synthetic/build_batch.pypolylogue/schemas/synthetic/runtime.pypolylogue/schemas/synthetic/selection.pypolylogue/schemas/synthetic/semantic_values.pypolylogue/showcase/qa_markdown.pypolylogue/showcase/qa_report.pypolylogue/showcase/qa_runner_stages.pypolylogue/showcase/qa_summary.pypolylogue/showcase/showcase_report_text.pypolylogue/showcase/workspace.pypolylogue/site/builder.pypolylogue/sources/drive_auth.pypolylogue/sources/drive_auth_support.pypolylogue/sources/parsers/claude.pypolylogue/sources/parsers/drive_support.pypolylogue/sources/token_store.pypolylogue/storage/action_event_rebuild_loading.pypolylogue/storage/backends/queries/attachment_records.pypolylogue/storage/session_product_aggregates.pypolylogue/ui/tui/screens/dashboard.pypyproject.toml
| from typing import Any | ||
|
|
||
| def run_vhs_capture(env, showcase_result, json_output: bool) -> None: | ||
|
|
||
| def run_vhs_capture(env: Any, showcase_result: Any, json_output: bool) -> None: |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Verify call sites and concrete result model used by run_vhs_capture.
rg -n -C3 --type=py '\brun_vhs_capture\('
rg -n -C3 --type=py '^class ShowcaseResult\b'Repository: Sinity/polylogue
Length of output: 1792
🏁 Script executed:
#!/bin/bash
# Examine the full implementation of run_vhs_capture in qa_capture.py
head -40 polylogue/cli/qa_capture.py | tail -30
# Check the full ShowcaseResult class definition
cat polylogue/showcase/showcase_runner_models.py | head -50 | tail -30Repository: Sinity/polylogue
Length of output: 1995
🏁 Script executed:
#!/bin/bash
# Find where run_vhs_capture is called and check the type of env parameter
rg -n -B5 'run_vhs_capture\(env' polylogue/cli/qa_finalization.py | head -30
# Check the function signature in qa_finalization that calls run_vhs_capture
rg -n -B10 'run_vhs_capture\(env' polylogue/cli/qa_finalization.py | grep -E '(^[0-9]+.*def |env:)'Repository: Sinity/polylogue
Length of output: 410
🏁 Script executed:
#!/bin/bash
# Find calls to finalize_qa_run to determine the actual type of env
rg -n 'finalize_qa_run\(' polylogue/Repository: Sinity/polylogue
Length of output: 240
🏁 Script executed:
#!/bin/bash
# Examine the call site in qa.py around line 161
sed -n '155,170p' polylogue/cli/commands/qa.pyRepository: Sinity/polylogue
Length of output: 478
🏁 Script executed:
#!/bin/bash
# Get more context to find the function signature containing this call
sed -n '100,165p' polylogue/cli/commands/qa.py | head -70Repository: Sinity/polylogue
Length of output: 2754
🏁 Script executed:
#!/bin/bash
# Find the function signature that contains this code
sed -n '1,160p' polylogue/cli/commands/qa.py | grep -A5 '^def ' | tail -20Repository: Sinity/polylogue
Length of output: 200
🏁 Script executed:
#!/bin/bash
# Find the definition of AppEnv
rg -n 'class AppEnv' polylogue/
rg -n 'AppEnv =' polylogue/Repository: Sinity/polylogue
Length of output: 340
🏁 Script executed:
#!/bin/bash
# Examine the AppEnv class definition
sed -n '16,60p' polylogue/cli/types.pyRepository: Sinity/polylogue
Length of output: 626
🏁 Script executed:
#!/bin/bash
# Find the UI class definition
rg -n 'class UI' polylogue/cli/types.pyRepository: Sinity/polylogue
Length of output: 42
🏁 Script executed:
#!/bin/bash
# Search for UI class definition across the codebase
rg -n 'class UI' polylogue/
rg -n 'from.*UI' polylogue/cli/types.pyRepository: Sinity/polylogue
Length of output: 250
🏁 Script executed:
#!/bin/bash
# Examine the UI class definition
sed -n '29,80p' polylogue/ui/__init__.pyRepository: Sinity/polylogue
Length of output: 2093
🏁 Script executed:
#!/bin/bash
# Let's get the complete function body of run_vhs_capture to ensure we've captured all attribute accesses
sed -n '8,35p' polylogue/cli/qa_capture.pyRepository: Sinity/polylogue
Length of output: 970
🏁 Script executed:
#!/bin/bash
# Get the complete function
sed -n '8,45p' polylogue/cli/qa_capture.pyRepository: Sinity/polylogue
Length of output: 1345
Use ShowcaseResult and Protocols to replace Any types for type safety.
The function accesses showcase_result.output_dir, showcase_result.results (both attributes of the ShowcaseResult dataclass), and env.ui.console.print(). Replacing Any with concrete types preserves these guarantees without runtime cost.
💡 Proposed diff
-from typing import Any
+from typing import Protocol
+
+from polylogue.showcase.showcase_runner_models import ShowcaseResult
+
+
+class _ConsoleLike(Protocol):
+ def print(self, message: str) -> None: ...
+
+
+class _UILike(Protocol):
+ console: _ConsoleLike
+
+
+class _EnvLike(Protocol):
+ ui: _UILike
-def run_vhs_capture(env: Any, showcase_result: Any, json_output: bool) -> None:
+def run_vhs_capture(env: _EnvLike, showcase_result: ShowcaseResult, json_output: bool) -> None:📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| from typing import Any | |
| def run_vhs_capture(env, showcase_result, json_output: bool) -> None: | |
| def run_vhs_capture(env: Any, showcase_result: Any, json_output: bool) -> None: | |
| from typing import Protocol | |
| from polylogue.showcase.showcase_runner_models import ShowcaseResult | |
| class _ConsoleLike(Protocol): | |
| def print(self, message: str) -> None: ... | |
| class _UILike(Protocol): | |
| console: _ConsoleLike | |
| class _EnvLike(Protocol): | |
| ui: _UILike | |
| def run_vhs_capture(env: _EnvLike, showcase_result: ShowcaseResult, json_output: bool) -> None: |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/cli/qa_capture.py` around lines 5 - 8, Replace the loose Any types
in run_vhs_capture with concrete types: use the existing ShowcaseResult
dataclass for the showcase_result parameter (it provides .output_dir and
.results) and define a small Protocol (e.g., EnvWithUI or UIEnv) for env that
exposes ui.console.print(...) so the type checker knows env.ui.console.print
exists; import typing.Protocol and annotate the function signature as
run_vhs_capture(env: EnvWithUI, showcase_result: ShowcaseResult, json_output:
bool) and update imports accordingly.
| import shutil | ||
| from datetime import datetime, timezone | ||
| from pathlib import Path | ||
| from typing import Any |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Replace env: Any with a minimal protocol contract.
env is structurally accessed (env.ui.console.print), so Any here unnecessarily disables checking. A lightweight Protocol preserves flexibility and type safety.
Proposed refactor
-from typing import Any
+from typing import Protocol
+
+
+class _ConsoleLike(Protocol):
+ def print(self, message: str) -> object: ...
+
+
+class _UILike(Protocol):
+ console: _ConsoleLike
+
+
+class _EnvLike(Protocol):
+ ui: _UILike
@@
def snapshot_results(
@@
- env: Any,
+ env: _EnvLike,
) -> None:
@@
def execute_snapshot_plan(
@@
- env: Any,
+ env: _EnvLike,
) -> bool:Also applies to: 61-61, 117-117
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/cli/qa_snapshot.py` at line 10, Replace the overly broad env: Any
typing by declaring a minimal Protocol that captures the attributes you actually
use (e.g., a Console protocol with a print method and a UI protocol that exposes
a console attribute), import Protocol from typing, and update the env parameter
annotations where used (the three occurrences in this file) to that Protocol;
ensure the new Protocol name is referenced in function signatures that currently
accept env so static checkers can verify usages like env.ui.console.print.
|
|
||
|
|
||
| def build_projection_semantic_facts(projection) -> ProjectionSemanticFacts: | ||
| def build_projection_semantic_facts(projection: Any) -> ProjectionSemanticFacts: |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Description: Find type definitions for Message, Conversation, Projection, and Summary models
echo "=== Searching for Projection model ==="
rg -n --type=py -C3 'class.*Projection.*:'
echo -e "\n=== Searching for Message model ==="
rg -n --type=py -C3 'class.*Message.*:' --glob '!**/test_*.py'
echo -e "\n=== Searching for Conversation model ==="
rg -n --type=py -C3 'class.*Conversation.*:'
echo -e "\n=== Searching for Summary model ==="
rg -n --type=py -C3 'class.*Summary.*:'Repository: Sinity/polylogue
Length of output: 50372
🏁 Script executed:
# First, let's read the semantic_facts.py file to see all builder functions
wc -l polylogue/lib/semantic_facts.pyRepository: Sinity/polylogue
Length of output: 95
🏁 Script executed:
# Read the entire semantic_facts.py file to see the builder functions
cat -n polylogue/lib/semantic_facts.pyRepository: Sinity/polylogue
Length of output: 12969
🏁 Script executed:
# Find the Summary model definition
rg -n --type=py 'class.*Summary.*:' polylogue/lib/ | head -20Repository: Sinity/polylogue
Length of output: 527
🏁 Script executed:
# Check imports in semantic_facts.py to see what's already imported
head -40 polylogue/lib/semantic_facts.pyRepository: Sinity/polylogue
Length of output: 1301
🏁 Script executed:
# Find the Conversation model
rg -n --type=py '^class Conversation\(' polylogue/ | grep -v test | head -10Repository: Sinity/polylogue
Length of output: 156
🏁 Script executed:
# Find ConversationProjection to understand projection type
rg -n --type=py 'class ConversationProjection' polylogue/Repository: Sinity/polylogue
Length of output: 195
🏁 Script executed:
# Check what imports would be needed
grep -n "from polylogue.lib" polylogue/lib/semantic_facts.pyRepository: Sinity/polylogue
Length of output: 238
🏁 Script executed:
# Check imports in the concrete type files to see if there's a circular dependency risk
head -30 polylogue/lib/conversation_models.pyRepository: Sinity/polylogue
Length of output: 1119
🏁 Script executed:
# Check message imports
head -30 polylogue/lib/message_models.pyRepository: Sinity/polylogue
Length of output: 1010
🏁 Script executed:
# Check projections imports
head -30 polylogue/lib/projections.pyRepository: Sinity/polylogue
Length of output: 966
🏁 Script executed:
# Search for any existing imports of Message, Conversation in semantic_facts.py context
rg -n "from polylogue.lib..*import.*Message|Conversation" polylogue/lib/semantic_facts.pyRepository: Sinity/polylogue
Length of output: 299
Consider replacing Any with concrete types for actual type safety.
All seven builder functions in this file use Any for input parameters, which mechanically satisfies mypy --strict but opts out of real type checking. The concrete domain models exist in the codebase and are directly importable:
projectionparameter →ConversationProjection(frompolylogue.lib.projections)messageparameter →Message(frompolylogue.lib.message_models)conversationparameter →Conversation(frompolylogue.lib.conversation_models)summaryparameter →ConversationSummary(frompolylogue.lib.conversation_models)
Using these concrete types would provide IDE autocomplete, document expected parameter structure, and protect against passing wrong object types—all without breaking changes.
Applies to: lines 33, 71, 102, 173, 197, 210, 227
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/lib/semantic_facts.py` at line 33, Replace the use of Any in the
seven builder functions with the concrete domain types: change the projection
parameter in build_projection_semantic_facts to ConversationProjection (import
from polylogue.lib.projections), change message parameters to Message (import
from polylogue.lib.message_models), and change conversation/summary parameters
to Conversation and ConversationSummary (import both from
polylogue.lib.conversation_models); update the function signatures and imports
accordingly so each builder (including build_projection_semantic_facts) uses the
specific types for full static checking and IDE autocomplete.
| substantive_messages = 0 | ||
| word_count = 0 | ||
| timestamps: list = [] | ||
| timestamps: list[Any] = [] |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Consider a more specific type for timestamp elements.
The list[Any] annotation is more explicit than an unannotated list, but the element type could be more precise. Based on the usage pattern (line 132 filters out None values, lines 141-145 use min/max and .total_seconds()), the timestamps appear to be datetime objects.
♻️ Suggested refinement
- timestamps: list[Any] = []
+ timestamps: list[datetime] = []Note: This assumes datetime is the correct type; verify based on message_fact.timestamp's actual type definition.
📝 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.
| timestamps: list[Any] = [] | |
| timestamps: list[datetime] = [] |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/lib/semantic_facts.py` at line 115, The annotation for the variable
`timestamps` is too broad (list[Any]); change it to a more specific datetime
type to reflect actual usage: declare `timestamps` as
list[Optional[datetime.datetime]] (or list[Optional[datetime]] if you import
datetime.datetime as datetime) to match values coming from
`message_fact.timestamp` (which can be None) and then after filtering Nones you
can treat the collection as list[datetime.datetime] for min/max and
.total_seconds() operations; also ensure `datetime` is imported at the top of
the module and update any related type hints accordingly.
| from typing import TYPE_CHECKING, Any | ||
|
|
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major
🧩 Analysis chain
🏁 Script executed:
cat -n polylogue/rendering/renderers/html_messages.py | head -100Repository: Sinity/polylogue
Length of output: 3859
🏁 Script executed:
rg -n "def build_rendered_message_payload" -A 30 polylogue/Repository: Sinity/polylogue
Length of output: 2010
Use Callable[[str], str] for render_html instead of Any.
Lines 56 and 82 use Any for the render_html parameter, but build_rendered_message_payload in polylogue/rendering/core_messages.py (line 14) expects Callable[[str], str] and calls it as render_html(text) where text is a string. Weaken the type constraints allows invalid callables to bypass static type checks.
Proposed typing fix
-from typing import TYPE_CHECKING, Any
+from collections.abc import Callable
+from typing import TYPE_CHECKING
@@
def build_projection_html_messages(
@@
- render_html: Any,
+ render_html: Callable[[str], str],
@@
def build_conversation_html_messages(
@@
- render_html: Any,
+ render_html: Callable[[str], str],🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/rendering/renderers/html_messages.py` around lines 6 - 7, Update
the type annotation for the render_html parameter in
polylogue/rendering/renderers/html_messages.py from Any to Callable[[str], str]:
import Callable from typing (add to the existing TYPE_CHECKING import) and
change the render_html parameter type in the functions referenced (the two
places around lines 56 and 82 where render_html is typed as Any) to
Callable[[str], str] so it matches build_rendered_message_payload’s expected
callable signature and prevents invalid callables from passing static type
checks.
| resolved_element_kind = element_kind | ||
|
|
||
| schema: dict | None | ||
| schema: dict[str, object] | None |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Verify schema type consistency across registry/model/selection modules.
rg -n -C2 --type=py 'def get_element_schema\(|def get_schema\(|schema:\s*dict\[str,\s*Any\]|schema:\s*dict\[str,\s*object\]'Repository: Sinity/polylogue
Length of output: 21338
Use dict[str, Any] for schema to match the return type of registry.get_element_schema() and codebase conventions.
The variable is assigned from registry.get_element_schema() which returns dict[str, Any] | None. The current narrowing to dict[str, object] is inconsistent with this source type and the predominant pattern across the synthetic module (runtime.py, relations.py, semantic_values.py, models.py, and core.py all use dict[str, Any] for schema types).
💡 Proposed diff
+from typing import Any
+
@@
- schema: dict[str, object] | None
+ schema: dict[str, Any] | None📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| schema: dict[str, object] | None | |
| schema: dict[str, Any] | None |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/schemas/synthetic/selection.py` at line 21, The schema annotation
in selection.py is incorrectly typed as dict[str, object] but should match
registry.get_element_schema() and the module convention by using dict[str, Any]
| None; update the variable/type annotation (named schema) in selection.py to
dict[str, Any] | None, import Any from typing if missing, and ensure any places
using schema remain compatible with dict[str, Any] (this aligns selection.py
with registry.get_element_schema() and the other synthetic module files).
| return ( | ||
| self.current_role if self.current_role in conversational else str(self.rng.choice(conversational)) | ||
| ) | ||
| return str(self.rng.choice(values)) | ||
| return self.current_role |
There was a problem hiding this comment.
Avoid blind stringification of observed values.
str(...) on arbitrary observed values can emit synthetic artifacts like "{...}" or "None"; prefer filtering to real strings first.
💡 Proposed diff
def _generate_role(self, schema: dict[str, Any]) -> str:
"""Generate a role value from observed values or cycle."""
# Prefer observed values from the schema
if values := schema.get("x-polylogue-values"):
+ string_values = [v for v in values if isinstance(v, str) and v]
# Filter to known conversational roles if present
- conversational = [v for v in values if v in {"user", "assistant", "human", "model", "system", "tool"}]
+ conversational = [
+ v for v in string_values if v in {"user", "assistant", "human", "model", "system", "tool"}
+ ]
if conversational:
- return (
- self.current_role if self.current_role in conversational else str(self.rng.choice(conversational))
- )
- return str(self.rng.choice(values))
+ return self.current_role if self.current_role in conversational else self.rng.choice(conversational)
+ if string_values:
+ return self.rng.choice(string_values)
return self.current_role
@@
# Use observed values if available
if values := schema.get("x-polylogue-values"):
- return str(self.rng.choice(values))
+ string_values = [v for v in values if isinstance(v, str) and v]
+ if string_values:
+ return self.rng.choice(string_values)Also applies to: 183-183
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/schemas/synthetic/semantic_values.py` around lines 140 - 144, The
code blindly calls str(...) on arbitrary sampled values (see self.current_role,
self.rng.choice(conversational) and self.rng.choice(values)), producing
artifacts like "None" or "{...}"; change the sampling logic to first filter
candidate pools (conversational and values) to only real strings (e.g., use
isinstance(..., str)) and pick from those; if the filtered list is empty, fall
back to a safe default (e.g., self.current_role or an explicit default) instead
of stringifying non-strings, and apply the same fix at the other occurrence also
noted around line 183.
| from pathlib import Path | ||
| from time import perf_counter | ||
| from typing import TYPE_CHECKING | ||
| from typing import TYPE_CHECKING, Any |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "SiteBuilder wrapper signatures:"
rg -n -C2 --type=py '\basync def _iter_conversation_indexes\b|\basync def _generate_conversation_page\b' polylogue/site/builder.py
echo
echo "Delegated archive-builder signatures:"
rg -n -C2 --type=py '\bdef iter_conversation_indexes_for_builder\b|\basync def generate_conversation_page_for_builder\b' polylogue/site/site_builder_archive.pyRepository: Sinity/polylogue
Length of output: 822
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "=== Checking builder.py imports and TYPE_CHECKING block ==="
head -20 polylogue/site/builder.py
echo
echo "=== Full signature of iter_conversation_indexes_for_builder ==="
rg -A 10 'async def iter_conversation_indexes_for_builder' polylogue/site/site_builder_archive.py
echo
echo "=== Full signature of generate_conversation_page_for_builder ==="
rg -A 5 'async def generate_conversation_page_for_builder' polylogue/site/site_builder_archive.py
echo
echo "=== Delegation calls in wrapper methods ==="
rg -B 2 -A 5 'iter_conversation_indexes_for_builder\|generate_conversation_page_for_builder' polylogue/site/builder.pyRepository: Sinity/polylogue
Length of output: 1742
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "=== TYPE_CHECKING block in builder.py ==="
rg -A 10 'if TYPE_CHECKING:' polylogue/site/builder.py
echo
echo "=== Wrapper method delegation calls ==="
sed -n '157,165p' polylogue/site/builder.py
echo "..."
sed -n '174,182p' polylogue/site/builder.pyRepository: Sinity/polylogue
Length of output: 1139
Avoid Any at these wrapper boundaries; it weakens the restored strict gate.
Lines 158–159 (backend: Any, repository: Any, -> Any) and line 175 (repository: Any) suppress type checking at key call boundaries. The delegated functions iter_conversation_indexes_for_builder and generate_conversation_page_for_builder already define concrete types (SQLiteBackend, ConversationRepository, AsyncIterator[ConversationIndex]), which are safely available in the TYPE_CHECKING block. With from __future__ import annotations, these can be used directly without runtime import cost.
Proposed fix
-from typing import TYPE_CHECKING, Any
+from collections.abc import AsyncIterator
+from typing import TYPE_CHECKING
@@
async def _iter_conversation_indexes(
- self, *, provider: str | None = None, backend: Any = None, repository: Any = None
- ) -> Any:
+ self,
+ *,
+ provider: str | None = None,
+ backend: SQLiteBackend | None = None,
+ repository: ConversationRepository | None = None,
+ ) -> AsyncIterator[ConversationIndex]:
@@
async def _generate_conversation_page(
- self, repository: Any, conversation: ConversationIndex, *, incremental: bool = True
+ self,
+ repository: ConversationRepository,
+ conversation: ConversationIndex,
+ *,
+ incremental: bool = True,
) -> str:🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/site/builder.py` at line 9, Replace the blanket Any annotations at
the wrapper boundaries with the concrete types already available under
TYPE_CHECKING: change iter_conversation_indexes_for_builder(backend: Any,
repository: Any) -> Any to use backend: SQLiteBackend, repository:
ConversationRepository, -> AsyncIterator[ConversationIndex], and change
generate_conversation_page_for_builder(repository: Any) to repository:
ConversationRepository; ensure from __future__ import annotations is present (or
keep it) and import SQLiteBackend, ConversationRepository, ConversationIndex,
and AsyncIterator inside the TYPE_CHECKING block so the names are available as
forward references without runtime imports, leaving function signatures using
those concrete types (symbols: iter_conversation_indexes_for_builder,
generate_conversation_page_for_builder, backend, repository, SQLiteBackend,
ConversationRepository, ConversationIndex, AsyncIterator).
| def load_cached_credentials( | ||
| *, | ||
| token_store, | ||
| token_store: Any, | ||
| credentials_cls: Any, | ||
| token_path: Path, | ||
| ) -> CachedCredentialState: |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Narrow token_store/creds contracts with Protocols instead of Any.
Line 68, Line 92, and Line 99 currently erase useful checks (load/save and credential lifecycle methods) in auth-critical helpers.
Also applies to: 92-100
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/sources/drive_auth_support.py` around lines 66 - 71, Define small
typing.Protocols and use them instead of Any: add a TokenStoreProtocol that
exposes load(path: Path) -> Optional[bytes] and save(path: Path, data: bytes) ->
None (or the exact load/save signatures used in this module) and a
CredentialsFactory/Instance Protocol that includes the classmethod used to
construct creds (e.g. from_authorized_user_info/from_json) and the instance
lifecycle members used in this file (properties/methods like valid, expired,
refresh(request), to_json() or to_authorized_user_info()). Then change the
signature of load_cached_credentials to accept token_store: TokenStoreProtocol
and credentials_cls: CredentialsFactoryProtocol and update any local variables
typed as Any (e.g. creds) to the new Protocol types so static checkers can
verify calls to load(), save(), refresh(), valid, expired, and to_json()/from_*.
| def _try_import_keyring() -> object | None: | ||
| try: | ||
| import keyring # type: ignore[import] | ||
| import keyring |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Description: Verify keyring typing and mypy status for this file
# Check if types-keyring is in dependencies
echo "=== Checking for types-keyring in dependencies ==="
rg -n "types-keyring" pyproject.toml uv.lock
# Check if this file is in mypy exclude list
echo -e "\n=== Checking mypy exclude list ==="
rg -A 50 "^\[tool\.mypy\]" pyproject.toml | rg -C 5 "exclude"
# Test mypy on this specific file
echo -e "\n=== Running mypy on token_store.py ==="
uv run mypy polylogue/sources/token_store.py --strictRepository: Sinity/polylogue
Length of output: 801
🏁 Script executed:
# Read token_store.py around line 82 to verify the import state
sed -n '75,90p' polylogue/sources/token_store.pyRepository: Sinity/polylogue
Length of output: 551
🏁 Script executed:
# Get full mypy configuration from pyproject.toml
rg -A 100 "^\[tool\.mypy\]" pyproject.tomlRepository: Sinity/polylogue
Length of output: 4302
🏁 Script executed:
# Search for other keyring imports in the codebase to see how they're handled
rg "import keyring" -B 1 -A 1Repository: Sinity/polylogue
Length of output: 199
Ensure untyped keyring import passes mypy checks.
The # type: ignore[import] comment has been removed from the keyring import at line 82. With mypy configured with strict = true, warn_unused_ignores = true, disallow_untyped_defs = true, and this file not in the mypy exclude list, the untyped keyring import will fail type checking.
To fix this, either:
- Add
types-keyringto project dependencies - Add
# type: ignore[import]back to the import statement - Add this file to the mypy exclude list
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@polylogue/sources/token_store.py` at line 82, The keyring import in
token_store.py is untyped and fails strict mypy; restore type checking by either
adding the import ignore or providing types: add `# type: ignore[import]` to the
`import keyring` line in token_store.py, or alternatively add `types-keyring` to
the project dependencies so mypy recognizes keyring's stubs (or add this file to
mypy's exclude list) — pick one of these fixes and apply it to the `import
keyring` statement to satisfy strict mypy.
Annotate four files held out of the mechanical mypy pass in #205 because straightforward `dict[str, Any]` / `self: Any` sprays surfaced design friction: - polylogue/lib/filters.py: ConversationFilter.list() shadows the builtin in its own return annotation. Resolved by referencing `builtins.list[...]` for the three methods that return lists. The three return-type annotations point at Conversation / ConversationSummary, deferred-imported under TYPE_CHECKING; calls into polylogue.lib.query_plan_execution still land in excluded territory and carry localized `# type: ignore[no-any-return]` markers that can drop once that module is cleaned. - polylogue/schemas/operator_annotations.py: JSON-schema walker. Use `dict[str, Any]` consistent with audit_walkers.py and audit_checks.py. - polylogue/schemas/synthetic/build_records.py and build_wire_formats.py: module-level functions bound onto SyntheticCorpus via class-body assignment. Adopt `self: Any` pattern already used in polylogue/schemas/synthetic/runtime.py plus `dict[str, Any]` for payloads. Gate grows from 385 → 389 files checked under mypy --strict. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Annotate four files held out of the mechanical mypy pass in #205 because straightforward `dict[str, Any]` / `self: Any` sprays surfaced design friction: - polylogue/lib/filters.py: ConversationFilter.list() shadows the builtin in its own return annotation. Resolved by referencing `builtins.list[...]` for the three methods that return lists. The three return-type annotations point at Conversation / ConversationSummary, deferred-imported under TYPE_CHECKING; calls into polylogue.lib.query_plan_execution still land in excluded territory and carry localized `# type: ignore[no-any-return]` markers that can drop once that module is cleaned. - polylogue/schemas/operator_annotations.py: JSON-schema walker. Use `dict[str, Any]` consistent with audit_walkers.py and audit_checks.py. - polylogue/schemas/synthetic/build_records.py and build_wire_formats.py: module-level functions bound onto SyntheticCorpus via class-body assignment. Adopt `self: Any` pattern already used in polylogue/schemas/synthetic/runtime.py plus `dict[str, Any]` for payloads. Gate grows from 385 → 389 files checked under mypy --strict. Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Three files each carrying a single mypy error that the #205 mechanical pass did not resolve — now cleaned and removed from the exclude list. - polylogue/cli/commands/check.py: `_make_schema_progress_callback()` wrapper missing return annotation. Impl (`check_support.py`) returns Any; annotate wrapper as `-> Any` to match. - polylogue/mcp/server.py: `extract_fenced_code` was wrapped in a lambda with a default argument, which mypy could not infer against `Callable[[str, str], list[dict[str, str]]]`. The wrapper was pure forwarding — pass `_extract_fenced_code` directly. - polylogue/rendering/formatting.py: `import yaml` triggered `import-untyped` because stubs were absent. Add `types-PyYAML>=6.0` under the `[project.optional-dependencies] dev` extra and re-lock uv.lock. File itself needs no source change. Gate grows from 389 → 392 files checked under mypy --strict. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Three files each carrying a single mypy error that the #205 mechanical pass did not resolve — now cleaned and removed from the exclude list. - polylogue/cli/commands/check.py: `_make_schema_progress_callback()` wrapper missing return annotation. Impl (`check_support.py`) returns Any; annotate wrapper as `-> Any` to match. - polylogue/mcp/server.py: `extract_fenced_code` was wrapped in a lambda with a default argument, which mypy could not infer against `Callable[[str, str], list[dict[str, str]]]`. The wrapper was pure forwarding — pass `_extract_fenced_code` directly. - polylogue/rendering/formatting.py: `import yaml` triggered `import-untyped` because stubs were absent. Add `types-PyYAML>=6.0` under the `[project.optional-dependencies] dev` extra and re-lock uv.lock. File itself needs no source change. Gate grows from 389 → 392 files checked under mypy --strict. Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
) ## Summary Re-introduce the `mypy --strict` type-checking gate that was removed in #174, and clean the mechanical-tier debt in the same PR so the exclude list starts at a realistic size. ## Problem After #174 the codebase had 1,764 strict errors across 232 files and no CI gate. Issue #188 set the direction but the work wasn't done. Two kinds of errors existed: - **Mechanical tier** (~500 errors): missing annotations, missing generic parameters, `Any`-typed returns. These are safe to fix in bulk. - **Design tier** (~1,200 errors): `attr-defined` (741, mostly the mixin-attribute pattern), `arg-type` (224, often real bugs), `union-attr`, `call-overload`. Each needs per-module thought and belongs in focused PRs. ## Solution ### `typecheck` CI job Runs `uv run mypy polylogue/` on every PR. Regressions fail CI: - new error in a covered file - new file that doesn't pass strict ### mypy version pinned `mypy>=1.17,<1.18` in the dev extras, matching the Nix devshell (1.17.1). Local and CI align. `uv.lock` regenerated (1.19.1 → 1.17.1). No more silent drift when a new mypy minor surfaces new errors. ### `devtools verify` runs mypy Between `ruff check` and `render-all`. Cold ~25s, warm ~1s. Pre-push hook now catches type regressions before CI. ### Mechanical cleanup in this PR Cleaned 53 files that only had mechanical errors. The exclude list dropped from 232 to 179 entries; gate coverage went from 332 → 385 files. Six files that *looked* mechanical but surfaced real issues on annotation stayed in exclude (details in the second commit). ### `CONTRIBUTING.md` Adds a "Widening Type-Check Coverage" section: pick a file, remove its exclude entry, fix errors, verify, commit. ### CI cleanup Removed the "typecheck is tracked debt" comment in `.github/workflows/ci.yml`. ## Follow-up The 179 files still in exclude fall into clusters that deserve dedicated PRs: - **Async/sync backend** (most `no-untyped-call` cascades): blocked by #190. - **Mixin-attribute Protocol declarations** (`attr-defined`): per-mixin PRs, each adding a `Protocol` for the consumer interface. - **`arg-type` / `union-attr`**: often real bugs — investigate per-case. ## Verification ``` nix develop -c mypy polylogue/ # Success: no issues found in 385 source files nix develop -c devtools verify # ruff format ok, ruff check ok, mypy ok, render-all ok # pytest 4947 passed (1 unrelated concurrency flake — #190) nix develop -c devtools verify --quick # ruff format ok, ruff check ok, mypy ok, render-all ok ``` Closes #188
…ns (#206) ## Summary - Four files held out of the #205 mechanical tier surfaced non-trivial annotation issues. This PR resolves each and removes them from the mypy `exclude`. - Gate grows from 385 → 389 files checked under `mypy --strict`. ## Problem During the #205 mechanical sweep I skipped four files where straight `dict[str, Any]` / `self: Any` sprays either failed or exposed design cruft: 1. `polylogue/lib/filters.py` — `ConversationFilter.list()` shadows the builtin in its own return annotation. `async def list(self) -> list[Conversation]:` fails because `list` in that scope resolves to the method, not the builtin. 2. `polylogue/schemas/operator_annotations.py` — JSON-schema walkers with untyped `dict` parameters. 3. `polylogue/schemas/synthetic/build_records.py` and `build_wire_formats.py` — module-level helpers bound to `SyntheticCorpus` via class-body assignment (`_generate_tree_json = _generate_tree_json`), with untyped `self` and `dict` parameters. ## Solution - `filters.py`: reference `builtins.list[Conversation]` / `builtins.list[ConversationSummary]` for the three methods that return lists and share the name. Add typed property returns for `_since_date`, `_until_date`, `_continuation`, `_sidechain`, `_has_branches`. Localized `# type: ignore[no-any-return]` on three call-sites that cross into `polylogue.lib.query_plan_execution` (still in the exclude list — these markers drop naturally when that module is cleaned). - `operator_annotations.py`: adopt `dict[str, Any]` consistent with sibling `polylogue/schemas/audit_walkers.py` and `audit_checks.py`. - `build_records.py`, `build_wire_formats.py`: adopt `self: Any` pattern already present in `polylogue/schemas/synthetic/runtime.py`, plus `dict[str, Any]` for JSON payloads. ## Verification Commands run: - `nix develop -c mypy --config-file pyproject.toml polylogue/` — `Success: no issues found in 389 source files` - `nix develop -c devtools verify --quick` — all checks passed (format, lint, mypy, render-all --check) - `git push` — pre-push hook (`devtools verify --quick`) passed Full `devtools verify` including pytest deferred to CI (local btrfs metadata pressure, unrelated to this change). 🤖 Generated with [Claude Code](https://claude.com/claude-code)
) After #174 the codebase had 1,764 strict errors across 232 files and no CI gate — #188 set the direction but the work wasn't done. Errors split into ~500 mechanical (missing annotations, missing generics, Any returns — safe to bulk-fix) and ~1,200 design-tier (`attr-defined` from the mixin pattern, `arg-type` often revealing real bugs, `union-attr`, `call-overload` — each needs per-module thought). Re-introduces the `typecheck` CI job running `uv run mypy polylogue/` on every PR, and pins `mypy>=1.17,<1.18` in dev extras so the local Nix devshell (1.17.1) and CI agree. `devtools verify` runs mypy between ruff and render-all (cold ~25s, warm ~1s), so the pre-push hook catches type regressions before CI. Mechanical cleanup lands in the same PR: 53 files cleaned and promoted into the gate, exclude list dropping from 232 to 179, coverage going from 332 to 385 files. Six files that looked mechanical but surfaced real design issues on annotation stayed in exclude for follow-up PRs. CONTRIBUTING.md grows a "Widening Type-Check Coverage" section documenting the workflow. The 179 remaining files cluster as: async/sync backend (blocked on #190), mixin-attribute Protocol declarations, and arg-type / union-attr (often real bugs — investigate per case). Verification: mypy clean on 385 files; devtools verify green. Closes #188
…ns (#206) Four files held out of the #205 mechanical sweep because straight `dict[str, Any]` / `self: Any` sprays either failed or exposed design cruft. `lib/filters.py`: `ConversationFilter.list()` shadowed the builtin in its own return annotation (`async def list(self) -> list[Conversation]` resolves `list` to the method, not the type). Reference `builtins.list[...]` on the three methods that return lists and share the name. Add typed property returns for the `_since_date` / `_until_date` / `_continuation` / `_sidechain` / `_has_branches` accessors. `schemas/operator_annotations.py`: adopt `dict[str, Any]` consistent with sibling `audit_walkers.py` and `audit_checks.py`. `schemas/synthetic/build_records.py` and `build_wire_formats.py`: adopt `self: Any` pattern already present in `runtime.py`, plus `dict[str, Any]` for JSON payloads. Gate grows from 385 → 389 files. Verification: mypy clean on 389 files; devtools verify --quick green.
Finishes the repo-wide mypy-strict cleanup started in #205 by removing the remaining per-file exclusions across `polylogue/`, `tests/`, and `devtools/`. The strict gate was previously green on a subset only; a long tail of excluded source, test, and maintenance files was slowing refactors, hiding real contract problems behind the exclude list, and leaving the repo half-green. Rather than patching around each symptom, the protocol-heavy and hydration-heavy modules get rewritten wholesale where needed so that runtime field contracts, provider metadata, projection/filter mixins, storage helpers, and large test support files become explicit and typed. CLI, pipeline, storage, source, product, and verification surfaces all pass `mypy --strict` and `ruff` without blanket ignores or compatibility shims. Also folds in cleanup work that surfaced during the sweep: disposable cache roots leaking into the top level get swept in `.envrc` / `flake.nix`, and the devshell entry MOTD — no longer useful — is replaced with a project status/help surface backed by tests. Verification: devtools verify green; mypy clean on the full polylogue + tests + devtools tree with no exclude entries.
) After #174 the codebase had 1,764 strict errors across 232 files and no CI gate — #188 set the direction but the work wasn't done. Errors split into ~500 mechanical (missing annotations, missing generics, Any returns — safe to bulk-fix) and ~1,200 design-tier (`attr-defined` from the mixin pattern, `arg-type` often revealing real bugs, `union-attr`, `call-overload` — each needs per-module thought). Re-introduces the `typecheck` CI job running `uv run mypy polylogue/` on every PR, and pins `mypy>=1.17,<1.18` in dev extras so the local Nix devshell (1.17.1) and CI agree. `devtools verify` runs mypy between ruff and render-all (cold ~25s, warm ~1s), so the pre-push hook catches type regressions before CI. Mechanical cleanup lands in the same PR: 53 files cleaned and promoted into the gate, exclude list dropping from 232 to 179, coverage going from 332 to 385 files. Six files that looked mechanical but surfaced real design issues on annotation stayed in exclude for follow-up PRs. CONTRIBUTING.md grows a "Widening Type-Check Coverage" section documenting the workflow. The 179 remaining files cluster as: async/sync backend (blocked on #190), mixin-attribute Protocol declarations, and arg-type / union-attr (often real bugs — investigate per case). Verification: mypy clean on 385 files; devtools verify green. Closes #188
…ns (#206) Four files held out of the #205 mechanical sweep because straight `dict[str, Any]` / `self: Any` sprays either failed or exposed design cruft. `lib/filters.py`: `ConversationFilter.list()` shadowed the builtin in its own return annotation (`async def list(self) -> list[Conversation]` resolves `list` to the method, not the type). Reference `builtins.list[...]` on the three methods that return lists and share the name. Add typed property returns for the `_since_date` / `_until_date` / `_continuation` / `_sidechain` / `_has_branches` accessors. `schemas/operator_annotations.py`: adopt `dict[str, Any]` consistent with sibling `audit_walkers.py` and `audit_checks.py`. `schemas/synthetic/build_records.py` and `build_wire_formats.py`: adopt `self: Any` pattern already present in `runtime.py`, plus `dict[str, Any]` for JSON payloads. Gate grows from 385 → 389 files. Verification: mypy clean on 389 files; devtools verify --quick green.
Finishes the repo-wide mypy-strict cleanup started in #205 by removing the remaining per-file exclusions across `polylogue/`, `tests/`, and `devtools/`. The strict gate was previously green on a subset only; a long tail of excluded source, test, and maintenance files was slowing refactors, hiding real contract problems behind the exclude list, and leaving the repo half-green. Rather than patching around each symptom, the protocol-heavy and hydration-heavy modules get rewritten wholesale where needed so that runtime field contracts, provider metadata, projection/filter mixins, storage helpers, and large test support files become explicit and typed. CLI, pipeline, storage, source, product, and verification surfaces all pass `mypy --strict` and `ruff` without blanket ignores or compatibility shims. Also folds in cleanup work that surfaced during the sweep: disposable cache roots leaking into the top level get swept in `.envrc` / `flake.nix`, and the devshell entry MOTD — no longer useful — is replaced with a project status/help surface backed by tests. Verification: devtools verify green; mypy clean on the full polylogue + tests + devtools tree with no exclude entries.
) After #174 the codebase had 1,764 strict errors across 232 files and no CI gate — #188 set the direction but the work wasn't done. Errors split into ~500 mechanical (missing annotations, missing generics, Any returns — safe to bulk-fix) and ~1,200 design-tier (`attr-defined` from the mixin pattern, `arg-type` often revealing real bugs, `union-attr`, `call-overload` — each needs per-module thought). Re-introduces the `typecheck` CI job running `uv run mypy polylogue/` on every PR, and pins `mypy>=1.17,<1.18` in dev extras so the local Nix devshell (1.17.1) and CI agree. `devtools verify` runs mypy between ruff and render-all (cold ~25s, warm ~1s), so the pre-push hook catches type regressions before CI. Mechanical cleanup lands in the same PR: 53 files cleaned and promoted into the gate, exclude list dropping from 232 to 179, coverage going from 332 to 385 files. Six files that looked mechanical but surfaced real design issues on annotation stayed in exclude for follow-up PRs. CONTRIBUTING.md grows a "Widening Type-Check Coverage" section documenting the workflow. The 179 remaining files cluster as: async/sync backend (blocked on #190), mixin-attribute Protocol declarations, and arg-type / union-attr (often real bugs — investigate per case). Verification: mypy clean on 385 files; devtools verify green. Closes #188
…ns (#206) Four files held out of the #205 mechanical sweep because straight `dict[str, Any]` / `self: Any` sprays either failed or exposed design cruft. `lib/filters.py`: `ConversationFilter.list()` shadowed the builtin in its own return annotation (`async def list(self) -> list[Conversation]` resolves `list` to the method, not the type). Reference `builtins.list[...]` on the three methods that return lists and share the name. Add typed property returns for the `_since_date` / `_until_date` / `_continuation` / `_sidechain` / `_has_branches` accessors. `schemas/operator_annotations.py`: adopt `dict[str, Any]` consistent with sibling `audit_walkers.py` and `audit_checks.py`. `schemas/synthetic/build_records.py` and `build_wire_formats.py`: adopt `self: Any` pattern already present in `runtime.py`, plus `dict[str, Any]` for JSON payloads. Gate grows from 385 → 389 files. Verification: mypy clean on 389 files; devtools verify --quick green.
Finishes the repo-wide mypy-strict cleanup started in #205 by removing the remaining per-file exclusions across `polylogue/`, `tests/`, and `devtools/`. The strict gate was previously green on a subset only; a long tail of excluded source, test, and maintenance files was slowing refactors, hiding real contract problems behind the exclude list, and leaving the repo half-green. Rather than patching around each symptom, the protocol-heavy and hydration-heavy modules get rewritten wholesale where needed so that runtime field contracts, provider metadata, projection/filter mixins, storage helpers, and large test support files become explicit and typed. CLI, pipeline, storage, source, product, and verification surfaces all pass `mypy --strict` and `ruff` without blanket ignores or compatibility shims. Also folds in cleanup work that surfaced during the sweep: disposable cache roots leaking into the top level get swept in `.envrc` / `flake.nix`, and the devshell entry MOTD — no longer useful — is replaced with a project status/help surface backed by tests. Verification: devtools verify green; mypy clean on the full polylogue + tests + devtools tree with no exclude entries.
|
@codex review |
|
Codex Review: Didn't find any major issues. Chef's kiss. ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
@codex review |
|
Codex Review: Didn't find any major issues. Can't wait for the next one! ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
Summary
Re-introduce the
mypy --stricttype-checking gate that was removed in #174, and clean the mechanical-tier debt in the same PR so the exclude list starts at a realistic size.Problem
After #174 the codebase had 1,764 strict errors across 232 files and no CI gate. Issue #188 set the direction but the work wasn't done. Two kinds of errors existed:
Any-typed returns. These are safe to fix in bulk.attr-defined(741, mostly the mixin-attribute pattern),arg-type(224, often real bugs),union-attr,call-overload. Each needs per-module thought and belongs in focused PRs.Solution
typecheckCI jobRuns
uv run mypy polylogue/on every PR. Regressions fail CI:mypy version pinned
mypy>=1.17,<1.18in the dev extras, matching the Nix devshell (1.17.1). Local and CI align.uv.lockregenerated (1.19.1 → 1.17.1). No more silent drift when a new mypy minor surfaces new errors.devtools verifyruns mypyBetween
ruff checkandrender-all. Cold ~25s, warm ~1s. Pre-push hook now catches type regressions before CI.Mechanical cleanup in this PR
Cleaned 53 files that only had mechanical errors. The exclude list dropped from 232 to 179 entries; gate coverage went from 332 → 385 files. Six files that looked mechanical but surfaced real issues on annotation stayed in exclude (details in the second commit).
CONTRIBUTING.mdAdds a "Widening Type-Check Coverage" section: pick a file, remove its exclude entry, fix errors, verify, commit.
CI cleanup
Removed the "typecheck is tracked debt" comment in
.github/workflows/ci.yml.Follow-up
The 179 files still in exclude fall into clusters that deserve dedicated PRs:
no-untyped-callcascades): blocked by refactor: unify async/sync storage backend semantics #190.attr-defined): per-mixin PRs, each adding aProtocolfor the consumer interface.arg-type/union-attr: often real bugs — investigate per-case.Verification
Closes #188