Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@ Run these commands from the repository root.
- Lint: `ruff check .`
- Check formatting: `black --check .`
- Apply formatting: `black .`
- Type check: `python -m basedpyright --pythonpath "$(python -c 'import sys; print(sys.executable)')"`
(covers all of `src/pt_snap_cli`; the gate is zero errors and warnings are
informational. `pyproject.toml` downgrades a listed set of rules to warnings
under `src/pt_snap_cli/snapshot/` until its annotations are fixed β€” do not
widen that list, shrink it)

`tests/run_tests.sh` is tied to a developer-specific Conda path and writes
coverage reports under `test_reports/`; use direct `pytest` commands unless
Expand Down
25 changes: 21 additions & 4 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -89,10 +89,27 @@ addopts = "-v --tb=short"

[tool.basedpyright]
pythonVersion = "3.13"
include = [
"src/pt_snap_cli/cli.py",
"src/pt_snap_cli/__init__.py",
]
include = ["src/pt_snap_cli"]
# basedpyright exits non-zero on warnings by default. The gate is "no errors";
# warnings (mostly reportUnknown* noise from third-party stubs) are informational.
# Without this, the result depends on how well-typed the installed typer happens
# to be, which is why the check passed in CI yet failed on developer machines.
failOnWarnings = false

# The snapshot runtime was migrated from its upstream project with its original
# loose annotations (issue #122, phase 3). Only the rules it currently violates are
# downgraded, and only under this root; every other module is checked at error
# level. Remove entries here as the annotations are fixed. Changes under
# src/pt_snap_cli/snapshot/ also require a PROVENANCE.md entry.
[[tool.basedpyright.executionEnvironments]]
root = "src/pt_snap_cli/snapshot"
reportMissingTypeArgument = "warning"
reportAssignmentType = "warning"
reportAttributeAccessIssue = "warning"
reportUninitializedInstanceVariable = "warning"
reportArgumentType = "warning"
reportIndexIssue = "warning"
reportImportCycles = "warning"

[tool.coverage.run]
source = ["pt_snap_cli"]
Expand Down
7 changes: 5 additions & 2 deletions src/pt_snap_cli/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,17 @@
import tempfile
from dataclasses import dataclass
from pathlib import Path
from typing import Any
from typing import Any, Literal

ENV_DB_PATH = "PT_SNAP_DB_PATH"
PROJECT_FOCUS_DIR = ".pt-snap"
PROJECT_FOCUS_FILE = "focus.json"
DB_PATH_KEY = "db_path"
DEVICE_ID_KEY = "device_id"

# Where a resolved database came from, in precedence order.
FocusSource = Literal["explicit", "env", "project", "global", "none"]


class FocusResolutionError(ValueError):
"""Raised when a configured focus cannot be read."""
Expand All @@ -27,7 +30,7 @@ class ResolvedFocus:
"""Resolved focus (database + optional device) with its source."""

db_path: Path | None
source: str
source: FocusSource
focus_file: Path | None = None
device_id: int | None = None

Expand Down
4 changes: 4 additions & 0 deletions src/pt_snap_cli/core/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,10 @@ class SourceChangedError(ImportExecutionError):
class SplitError(PtSnapCoreError):
"""A phase-identifying split failure suitable for CLI presentation."""

phase: SplitPhase
source_path: Path
detail: str

def __init__(self, phase: SplitPhase, source_path: Path, detail: str) -> None:
self.phase = phase
self.source_path = source_path
Expand Down
3 changes: 2 additions & 1 deletion src/pt_snap_cli/core/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
from pathlib import Path
from typing import Any, Literal

FocusSource = Literal["explicit", "env", "project", "global", "none"]
from pt_snap_cli.config import FocusSource

CacheMissReason = Literal[
"database_missing",
"database_invalid",
Expand Down
21 changes: 10 additions & 11 deletions src/pt_snap_cli/core/query_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,18 +72,17 @@ def list_templates(
if category is not None
else list_queries_with_details()
)
return [
TemplateSummary(
name=row["name"],
description=row["description"],
category=(
get_query(row["name"]).category
if get_query(row["name"]) is not None
else category
),
summaries: list[TemplateSummary] = []
for row in template_rows:
template = get_query(row["name"])
summaries.append(
TemplateSummary(
name=row["name"],
description=row["description"],
category=template.category if template is not None else category,
)
)
for row in template_rows
]
return summaries

def get_template_info(self, name: str) -> TemplateInfo:
template = get_query(name)
Expand Down
2 changes: 1 addition & 1 deletion src/pt_snap_cli/core/split_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ def _slice_device(
try:
raw_dir = stage / f".device-{device}"
raw_dir.mkdir()
event_count = len(cast(list[object], representation["device_traces"])[device])
event_count = len(cast(list[list[object]], representation["device_traces"])[device])
hooker = SliceDumpHooker(
dump_dir=str(raw_dir),
num_of_slices=slices if slices is not None else 1,
Expand Down
8 changes: 5 additions & 3 deletions src/pt_snap_cli/query/mapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def __init__(self):
"hex": lambda x: hex(x) if isinstance(x, int) else x,
"datetime": lambda x: x,
}
self._model_factories: dict[str, Callable[[dict], Any]] = {}
self._model_factories: dict[str, Callable[[dict[str, Any]], Any]] = {}

def register_type_converter(self, type_name: str, converter: Callable[[Any], Any]) -> None:
"""Register a type converter.
Expand All @@ -31,7 +31,9 @@ def register_type_converter(self, type_name: str, converter: Callable[[Any], Any
"""
self._type_converters[type_name] = converter

def register_model_factory(self, model_name: str, factory: Callable[[dict], Any]) -> None:
def register_model_factory(
self, model_name: str, factory: Callable[[dict[str, Any]], Any]
) -> None:
"""Register a model factory.

Args:
Expand Down Expand Up @@ -179,7 +181,7 @@ def register_type_converter(

def register_model_factory(
model_name: str,
factory: Callable[[dict], Any],
factory: Callable[[dict[str, Any]], Any],
) -> None:
"""Register a model factory with default mapper.

Expand Down
14 changes: 10 additions & 4 deletions src/pt_snap_cli/query/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import warnings
from collections.abc import Callable
from pathlib import Path
from typing import Any

from pt_snap_cli.query.config import QueryConfig, QueryTemplate

Expand All @@ -15,13 +16,18 @@ class QueryRegistry:
"""Registry for predefined query templates."""

_instance: QueryRegistry | None = None
# Initialized in __new__ (the singleton has no __init__ so repeated
# QueryRegistry() calls cannot wipe the shared state).
_queries: dict[str, QueryTemplate] # pyright: ignore[reportUninitializedInstanceVariable]
_factories: dict[str, QueryFactory] # pyright: ignore[reportUninitializedInstanceVariable]

def __new__(cls) -> QueryRegistry:
"""Singleton pattern for global registry."""
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance._queries: dict[str, QueryTemplate] = {}
cls._instance._factories: dict[str, QueryFactory] = {}
instance = super().__new__(cls)
instance._queries = {}
instance._factories = {}
cls._instance = instance
return cls._instance

@classmethod
Expand Down Expand Up @@ -175,7 +181,7 @@ def get_query(name: str) -> QueryTemplate | None:
return _registry.get(name)


def get_template_info(name: str) -> dict | None:
def get_template_info(name: str) -> dict[str, Any] | None:
"""Get detailed information about a template.

Args:
Expand Down
Loading