Skip to content
Open
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
14 changes: 7 additions & 7 deletions .github/scripts/check_critical_coverage.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,15 @@
# These are independent floors, not an average that another module can offset.
# Keep the original three floors unchanged when extending the risk inventory.
CRITICAL_FLOORS = {
"src/pt_snap_cli/core/snapshot_import_backend.py": 90,
"src/pt_snap_cli/core/importing/snapshot_import_backend.py": 90,
"src/pt_snap_cli/snapshot/simulate/simulated_caching_allocator.py": 88,
"src/pt_snap_cli/snapshot/simulate/snapshot_mutator.py": 84,
"src/pt_snap_cli/core/import_metadata_contract.py": 100,
"src/pt_snap_cli/core/import_metadata.py": 90,
"src/pt_snap_cli/core/split_service.py": 90,
"src/pt_snap_cli/core/focus_service.py": 90,
"src/pt_snap_cli/core/skill_service.py": 90,
"src/pt_snap_cli/core/snapshot_cache.py": 90,
"src/pt_snap_cli/core/importing/import_metadata_contract.py": 100,
"src/pt_snap_cli/core/importing/import_metadata.py": 90,
"src/pt_snap_cli/core/splitting/split_service.py": 90,
"src/pt_snap_cli/core/analysis/focus_service.py": 90,
"src/pt_snap_cli/core/analysis/skill_service.py": 90,
"src/pt_snap_cli/core/cache/snapshot_cache.py": 90,
"src/pt_snap_cli/snapshot/representation.py": 95,
}

Expand Down
14 changes: 7 additions & 7 deletions .github/workflows/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,15 @@ inventory. A high average cannot compensate for a single file below its floor.

| Runtime module (`src/pt_snap_cli/`) | Minimum line + branch coverage |
| --- | --- |
| `core/snapshot_import_backend.py` | 90% |
| `core/importing/snapshot_import_backend.py` | 90% |
| `snapshot/simulate/simulated_caching_allocator.py` | 88% |
| `snapshot/simulate/snapshot_mutator.py` | 84% |
| `core/import_metadata_contract.py` | 100% |
| `core/import_metadata.py` | 90% |
| `core/split_service.py` | 90% |
| `core/focus_service.py` | 90% |
| `core/skill_service.py` | 90% |
| `core/snapshot_cache.py` | 90% |
| `core/importing/import_metadata_contract.py` | 100% |
| `core/importing/import_metadata.py` | 90% |
| `core/splitting/split_service.py` | 90% |
| `core/analysis/focus_service.py` | 90% |
| `core/analysis/skill_service.py` | 90% |
| `core/cache/snapshot_cache.py` | 90% |
| `snapshot/representation.py` | 95% |

The checker requires `.coverage`, branch data, every listed source file, measured
Expand Down
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ may point to an existing Chromium executable instead of downloading one.

- Type checking covers all `src/pt_snap_cli`, including `snapshot/`. Zero errors
is the gate; warnings are informational. Preserve the file-level Any/Unknown
error gates in `api.py`, `core/models.py`, and `snapshot/representation.py`;
error gates in `api.py`, `core/common/models.py`, and `snapshot/representation.py`;
do not downgrade snapshot through an `executionEnvironments` exception.
- Pytest treats `ResourceWarning` and `PytestUnraisableExceptionWarning` as
errors. Ownership/teardown guidance lives in [tests](tests/AGENTS.md).
Expand Down
12 changes: 6 additions & 6 deletions benchmarks/active_at_event_capacity.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,12 @@
from dataclasses import asdict
from pathlib import Path

from pt_snap_cli.core.dataset_contract import ACTION_NAMES, BLOCK_STATES
from pt_snap_cli.core.dataset_sources import QueryBudget
from pt_snap_cli.core.errors import QueryExecutionError
from pt_snap_cli.core.models import ImportMetadata
from pt_snap_cli.core.native_dataset_contract import NATIVE_FORMAT, cache_identity
from pt_snap_cli.core.query_service import QueryService
from pt_snap_cli.core.analysis.query_service import QueryService
from pt_snap_cli.core.common.errors import QueryExecutionError
from pt_snap_cli.core.common.models import ImportMetadata
from pt_snap_cli.core.dataset.dataset_contract import ACTION_NAMES, BLOCK_STATES
from pt_snap_cli.core.dataset.dataset_sources import QueryBudget
from pt_snap_cli.core.dataset.native_dataset_contract import NATIVE_FORMAT, cache_identity

SCHEMA = """CREATE TABLE dictionary ("table" TEXT,"column" TEXT,"key" TEXT,"value" TEXT);
CREATE TABLE trace_entry_0 (id INTEGER PRIMARY KEY,action INTEGER,address INTEGER,
Expand Down
6 changes: 3 additions & 3 deletions benchmarks/baseline_import.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,11 +124,11 @@ def _run_import_once(snapshot: Path, output_dir: Path, device: int) -> RunResult
"-c",
f"""
import logging; logging.disable(logging.CRITICAL)
import pt_snap_cli.core.import_metadata as import_metadata
import pt_snap_cli.core.importing.import_metadata as import_metadata
import resource
import sys
from benchmarks.baseline_import import _max_rss_kb
from pt_snap_cli.core.import_service import ImportOptions, ImportService
from pt_snap_cli.core.importing.import_service import ImportOptions, ImportService
from pathlib import Path
if not import_metadata.__version__:
import_metadata.__version__ = "benchmark"
Expand Down Expand Up @@ -273,7 +273,7 @@ def _correctness_summary(output_dir: Path, device: int) -> dict:


def _profile_import(snapshot: Path, output_dir: Path, device: int, top_n: int = 20) -> str:
from pt_snap_cli.core.import_service import ImportOptions, ImportService
from pt_snap_cli.core.importing.import_service import ImportOptions, ImportService

service = ImportService()
options = ImportOptions(
Expand Down
7 changes: 4 additions & 3 deletions benchmarks/dataset_import_baseline.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,9 +128,10 @@ def require_owned_child(args, identity: dict) -> None:

def child(args) -> dict:
from pt_snap_cli.api import SnapshotAnalyzer
from pt_snap_cli.core import import_service, sharded_replay_service
from pt_snap_cli.core.import_service import ImportService
from pt_snap_cli.core.models import ImportOptions
from pt_snap_cli.core.common.models import ImportOptions
from pt_snap_cli.core.importing import import_service
from pt_snap_cli.core.importing.import_service import ImportService
from pt_snap_cli.core.splitting import sharded_replay_service
from pt_snap_cli.snapshot.tools.adaptors import snapshot2db

logging.disable(logging.CRITICAL)
Expand Down
4 changes: 2 additions & 2 deletions benchmarks/export_validation_memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@
from contextlib import closing
from pathlib import Path

from pt_snap_cli.core.msinsight_export import DEFAULT_CAPACITY, _validate_shards
from pt_snap_cli.core.sharded_replay_service import ShardedReplayResult
from pt_snap_cli.core.importing.msinsight_export import DEFAULT_CAPACITY, _validate_shards
from pt_snap_cli.core.splitting.sharded_replay_service import ShardedReplayResult
from pt_snap_cli.snapshot.tools.adaptors.sharded_replay import ReplaySlice


Expand Down
2 changes: 1 addition & 1 deletion benchmarks/interop_acceptance.py
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ def require(condition: bool, name: str) -> None:

def compare_artifact(root: Path, device: int, reference: Path) -> dict:
from pt_snap_cli.api import SnapshotAnalyzer
from pt_snap_cli.core.report_service import ReportService
from pt_snap_cli.core.analysis.report_service import ReportService

root = canonical(root)
reference = canonical(reference)
Expand Down
12 changes: 6 additions & 6 deletions benchmarks/lifecycle_query_plans.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,12 @@
from pathlib import Path
from unittest.mock import patch

from pt_snap_cli.core import dataset_lifecycle_sql
from pt_snap_cli.core.context_cache import ContextCache
from pt_snap_cli.core.dataset_global import global_query
from pt_snap_cli.core.dataset_lifecycle_scratch import _ScratchSources
from pt_snap_cli.core.dataset_resolver import DatasetResolver
from pt_snap_cli.core.dataset_sources import DatasetSourceResolver, QueryBudget
from pt_snap_cli.core.cache.context_cache import ContextCache
from pt_snap_cli.core.dataset.dataset_resolver import DatasetResolver
from pt_snap_cli.core.dataset.dataset_sources import DatasetSourceResolver, QueryBudget
from pt_snap_cli.core.dataset.lifecycle import dataset_lifecycle_sql
from pt_snap_cli.core.dataset.lifecycle.dataset_lifecycle_scratch import _ScratchSources
from pt_snap_cli.core.dataset.query.dataset_global import global_query
from pt_snap_cli.query.registry import get_query


Expand Down
2 changes: 1 addition & 1 deletion docs/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ in scoped AGENTS guides, not in user walkthroughs.

| Topic | Source of truth |
| --- | --- |
| Root commands/help/JSON | `cli.py`, `cli_output.py`, `core/json_codec.py`, `core/error_codes.py` |
| Root commands/help/JSON | `cli.py`, `cli_output.py`, `core/common/json_codec.py`, `core/common/error_codes.py` |
| Reports and skill commands | `cli_reports.py`, `cli_skills.py` and owning core services |
| API/lifecycle | `api.py`, core result models, CLI/API contract tests |
| Focus and read-only inspection | `config.py`, `context.py`, focus/overview/metadata services |
Expand Down
4 changes: 2 additions & 2 deletions docs/en/sharded-snapshotdb.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ stack-statistics semantics are explicitly versioned in the querying guide. The P
complete compatibility-v1 manifest or directory as focus. The `complete` gate
applies only to datasets, not to legacy single-DB analysis.

`pt_snap_cli.core.dataset_contract` provides `parse_manifest`,
`pt_snap_cli.core.dataset.dataset_contract` provides `parse_manifest`,
`validate_event_ids`, `validate_dataset`, immutable manifest/device/slice models,
`QueryScope`, and `DatasetContractError` (`location`, `code`). Producers can share
the same prepublication contract with readers. Validation never loads pickle,
Expand Down Expand Up @@ -185,7 +185,7 @@ below; the explicit [P3 support matrix](querying.md#dataset-global-built-in-supp
and [point-event sources](querying.md#dataset-point-event-attribution) define execution.

```python
from pt_snap_cli.core.dataset_contract import QueryScope, validate_dataset
from pt_snap_cli.core.dataset.dataset_contract import QueryScope, validate_dataset

inspection = validate_dataset("/capture/snapshot.pkl.msinsight")
QueryScope("event_range", device_id=0, start_event_id=1, end_event_id=3).validate(
Expand Down
2 changes: 1 addition & 1 deletion docs/en/snapshot-analyzer-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ The caller must call `shared_cache.close()` after all borrowers have finished:

```python
from contextlib import closing
from pt_snap_cli.core.context_cache import ContextCache
from pt_snap_cli.core.cache.context_cache import ContextCache

with closing(ContextCache()) as shared_cache:
with SnapshotAnalyzer(Path("/path/to/snapshot.db"), context_cache=shared_cache) as first:
Expand Down
4 changes: 2 additions & 2 deletions docs/zh/sharded-snapshotdb.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
v1/v2 分析入口保留;P3 真实事件 peak/gap 与全部 action 完整文本栈统计语义在查询指南明确版本化。下述 P1 reader 新增将 complete 兼容 v1 manifest 或目录作为
focus;`complete` 门槛只约束数据集,不约束旧单库分析。

`pt_snap_cli.core.dataset_contract` 提供 `parse_manifest`、`validate_event_ids`、
`pt_snap_cli.core.dataset.dataset_contract` 提供 `parse_manifest`、`validate_event_ids`、
`validate_dataset`、不可变 manifest/device/slice 模型、`QueryScope` 和带
`location/code` 的 `DatasetContractError`。生产端可在发布前与读取端共用同一合同。
校验不加载 pickle、不创建缺失数据库、不迁移 SQLite、不写 focus。
Expand Down Expand Up @@ -150,7 +150,7 @@ dictionary 的十进制整数 key 以文本存储,使用真实带设备后缀
及[定点来源](querying.md#数据集定点事件归因)。

```python
from pt_snap_cli.core.dataset_contract import QueryScope, validate_dataset
from pt_snap_cli.core.dataset.dataset_contract import QueryScope, validate_dataset

inspection = validate_dataset("/capture/snapshot.pkl.msinsight")
QueryScope("event_range", device_id=0, start_event_id=1, end_event_id=3).validate(
Expand Down
2 changes: 1 addition & 1 deletion docs/zh/snapshot-analyzer-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ with SnapshotAnalyzer(Path("/path/to/snapshot.db")) as scoped_analyzer:

```python
from contextlib import closing
from pt_snap_cli.core.context_cache import ContextCache
from pt_snap_cli.core.cache.context_cache import ContextCache

with closing(ContextCache()) as shared_cache:
with SnapshotAnalyzer(Path("/path/to/snapshot.db"), context_cache=shared_cache) as first:
Expand Down
4 changes: 2 additions & 2 deletions src/pt_snap_cli/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ Parent scope: [source/distribution](../AGENTS.md).
Preserve `_safe_call` handling for argument parsing as well as domain errors;
successful service calls are not enough to validate JSON mode.
- Adapters may format or translate public errors, but service behavior belongs
in core. Use existing serializers in `core/json_codec.py` and
`core/query_service.py` instead of constructing a second template schema.
in core. Use existing serializers in `core/common/json_codec.py` and
`core/analysis/query_service.py` instead of constructing a second template schema.
- `SnapshotAnalyzer.set_focus()` changes validated session state; CLI focus
persistence goes through `FocusService`/`Config`. Preserve their normalized
shared behavior without making the API write project focus implicitly.
Expand Down
4 changes: 2 additions & 2 deletions src/pt_snap_cli/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@
QueryService,
TemplateNotFoundError,
)
from pt_snap_cli.core.context_cache import ContextCache
from pt_snap_cli.core.query_limits import QueryLimits
from pt_snap_cli.core.cache.context_cache import ContextCache
from pt_snap_cli.core.common.query_limits import QueryLimits


class TemplateSummaryPayload(TypedDict):
Expand Down
6 changes: 3 additions & 3 deletions src/pt_snap_cli/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,9 @@
json_error,
json_success,
)
from pt_snap_cli.core.error_codes import DATABASE_NOT_FOUND, ERROR, INVALID_PARAMETER
from pt_snap_cli.core.errors import InvalidParameterError
from pt_snap_cli.core.query_limits import QueryLimits
from pt_snap_cli.core.common.error_codes import DATABASE_NOT_FOUND, ERROR, INVALID_PARAMETER
from pt_snap_cli.core.common.errors import InvalidParameterError
from pt_snap_cli.core.common.query_limits import QueryLimits
from pt_snap_cli.query.config import OUTPUT_COLUMN_OPTIONAL
from pt_snap_cli.query.executor import reported_sql_limit
from pt_snap_cli.query.registry import discover_categories, get_query
Expand Down Expand Up @@ -246,7 +246,7 @@
] = None,
) -> None:
"""PyTorch Memory Snapshot Analysis Tool."""
_JSON_MODE.set(False)

Check warning on line 249 in src/pt_snap_cli/cli.py

View workflow job for this annotation

GitHub Actions / Lint & Format

Result of call expression is of type "Token[bool]" and is not used; assign to variable "_" if this is intentional (reportUnusedCallResult)


@app.command("focus")
Expand Down Expand Up @@ -681,7 +681,7 @@
typer.echo(f"Devices: {info.devices}")
typer.echo(f"Dataset Support: {json.dumps(info.dataset_support, sort_keys=True)}")
typer.echo(
"Semantics Version: "

Check warning on line 684 in src/pt_snap_cli/cli.py

View workflow job for this annotation

GitHub Actions / Lint & Format

Implicit string concatenation not allowed (reportImplicitStringConcatenation)
f"{info.semantics_version if info.semantics_version is not None else 'none'}"
)
typer.echo()
Expand Down Expand Up @@ -1043,7 +1043,7 @@
try:
# Typer 0.27's non-standalone _main catches Exit and returns the
# code. Discarding that value made every domain _error() exit 0.
rv = app(standalone_mode=False)

Check warning on line 1046 in src/pt_snap_cli/cli.py

View workflow job for this annotation

GitHub Actions / Lint & Format

Type of "rv" is Any (reportAny)
code = rv if isinstance(rv, int) else 0
except ClickException as exc:
if _json_requested():
Expand Down
6 changes: 3 additions & 3 deletions src/pt_snap_cli/cli_output.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,13 @@
dumps_json,
json_error,
)
from pt_snap_cli.core.error_codes import ERROR
from pt_snap_cli.core.models import SKILL_RESTART_ACTIONS, SKILL_RESTART_HINT
from pt_snap_cli.core.skill_service import (
from pt_snap_cli.core.analysis.skill_service import (
format_skill_install_target,
format_skill_location,
human_skill_summary,
)
from pt_snap_cli.core.common.error_codes import ERROR
from pt_snap_cli.core.common.models import SKILL_RESTART_ACTIONS, SKILL_RESTART_HINT

# Typer 0.27+ vendors Click, so its context cannot be read via click.get_current_context.
JSON_MODE: ContextVar[bool] = ContextVar("pt_snap_json_mode", default=False)
Expand Down Expand Up @@ -142,19 +142,19 @@
else:
typer.echo(" Attribution: complete for the effective filters.")
typer.echo(
f" Parameters: include_static={report.effective_params.get('include_static')}, "

Check warning on line 145 in src/pt_snap_cli/cli_output.py

View workflow job for this annotation

GitHub Actions / Lint & Format

Implicit string concatenation not allowed (reportImplicitStringConcatenation)
f"min_size={report.effective_params.get('min_size')}, "
f"top_n={report.effective_params.get('top_n')}"
)
typer.echo(
f" Percentage denominator: {report.percent_denominator}={report.included_bytes} bytes "

Check warning on line 150 in src/pt_snap_cli/cli_output.py

View workflow job for this annotation

GitHub Actions / Lint & Format

Implicit string concatenation not allowed (reportImplicitStringConcatenation)
"(included groups after filtering/top_n; not all active memory or block counts)."
)
coverage = (
f"{report.coverage_percent:.4f}%" if report.coverage_percent is not None else "unknown"
)
typer.echo(
f" Active coverage at event {report.event_id}: {coverage} "

Check warning on line 157 in src/pt_snap_cli/cli_output.py

View workflow job for this annotation

GitHub Actions / Lint & Format

Implicit string concatenation not allowed (reportImplicitStringConcatenation)
f"(included={report.included_bytes} bytes, active={report.active_bytes_at_event} bytes)."
)
if not report.callstack_groups:
Expand All @@ -167,14 +167,14 @@
typer.echo(f" {row.get('callstack')}")
if "stack_id" in row:
typer.echo(
f" stack_id={row['stack_id']} kind={row.get('stack_kind')} "

Check warning on line 170 in src/pt_snap_cli/cli_output.py

View workflow job for this annotation

GitHub Actions / Lint & Format

Implicit string concatenation not allowed (reportImplicitStringConcatenation)
f"stack_truncated={row.get('stack_truncated')} "
f"stack_bytes={row.get('stack_bytes')} "
f"stack_original_bytes={row.get('stack_original_bytes')}"
)
if row.get("stack_kind") == "captured":
typer.echo(
" Full text: query event with "

Check warning on line 177 in src/pt_snap_cli/cli_output.py

View workflow job for this annotation

GitHub Actions / Lint & Format

Implicit string concatenation not allowed (reportImplicitStringConcatenation)
f"id={row.get('stack_event_id')}, omit stack_bytes, same database/device."
)

Expand Down
6 changes: 3 additions & 3 deletions src/pt_snap_cli/cli_reports.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,9 @@
TemplateNotFoundError,
TemplateRenderError,
)
from pt_snap_cli.core.error_codes import DATABASE_NOT_FOUND, INVALID_PARAMETER
from pt_snap_cli.core.errors import PtSnapCoreError
from pt_snap_cli.core.query_limits import QueryLimits
from pt_snap_cli.core.common.error_codes import DATABASE_NOT_FOUND, INVALID_PARAMETER
from pt_snap_cli.core.common.errors import PtSnapCoreError
from pt_snap_cli.core.common.query_limits import QueryLimits
from pt_snap_cli.memory_tree_render import render_memory_tree

report_app = typer.Typer(help="Generate memory analysis reports")
Expand Down
4 changes: 2 additions & 2 deletions src/pt_snap_cli/cli_skills.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@
SkillNotFoundError,
SkillService,
)
from pt_snap_cli.core.error_codes import INVALID_PARAMETER
from pt_snap_cli.core.skill_service import parse_host_option
from pt_snap_cli.core.analysis.skill_service import parse_host_option
from pt_snap_cli.core.common.error_codes import INVALID_PARAMETER

skill_app = typer.Typer(help="Manage bundled agent skills", no_args_is_help=True)

Expand Down
8 changes: 4 additions & 4 deletions src/pt_snap_cli/completion.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@

def complete_skill_names() -> list[str]:
"""Return bundled agent skill names for shell completion."""
from pt_snap_cli.core.errors import SkillCatalogError
from pt_snap_cli.core.skill_service import SkillService
from pt_snap_cli.core.analysis.skill_service import SkillService
from pt_snap_cli.core.common.errors import SkillCatalogError

try:
return [skill.name for skill in SkillService().list_catalog()]
Expand All @@ -37,7 +37,7 @@

def complete_skill_targets() -> list[str]:
"""Return supported skill host names for shell completion."""
from pt_snap_cli.core.models import SKILL_HOSTS
from pt_snap_cli.core.common.models import SKILL_HOSTS

return list(SKILL_HOSTS)

Expand All @@ -55,8 +55,8 @@
if project_focus:
try:
with open(project_focus) as f:
data = json.load(f)

Check warning on line 58 in src/pt_snap_cli/completion.py

View workflow job for this annotation

GitHub Actions / Lint & Format

Type of "data" is Any (reportAny)
db_path = data.get(DB_PATH_KEY) or data.get("current_db_path")

Check warning on line 59 in src/pt_snap_cli/completion.py

View workflow job for this annotation

GitHub Actions / Lint & Format

Type of "db_path" is Any (reportAny)
if db_path:
return Path(db_path).expanduser()
except (json.JSONDecodeError, OSError):
Expand All @@ -75,7 +75,7 @@
return []

try:
from pt_snap_cli.core.dataset_resolver import DatasetResolver
from pt_snap_cli.core.dataset.dataset_resolver import DatasetResolver

devices = DatasetResolver().completion_device_ids(db_path)
if devices is not None:
Expand Down
40 changes: 28 additions & 12 deletions src/pt_snap_cli/core/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,37 @@ Parent scope: [package runtime](../AGENTS.md).
Core owns product semantics over config, Context, queries and snapshot mechanisms.
CLI/API adapters consume its results and errors; presentation stays in adapters.


Core modules are grouped by responsibility:

| Package | Responsibility |
| --- | --- |
| `common/` | Shared result/error contracts, serialization and query budgets |
| `analysis/` | Focus, query, overview, capability and report services |
| `cache/` | Context lifetime and snapshot cache identity |
| `dataset/` | Dataset contracts, source resolution and validation |
| `dataset/query/` | Dataset query reduction, attribution and frame trees |
| `dataset/lifecycle/` | Lifecycle SQL, attached connections and scratch storage |
| `importing/` | Import orchestration, metadata, publication, integrity and export |
| `splitting/` | Snapshot splitting and sharded replay |

The public services and result types remain exported by `pt_snap_cli.core`.

## Service Boundaries

| Files | Responsibility |
| --- | --- |
| `focus_service.py` | Resolve/validate database and device; explicit project/global focus writes |
| `context_cache.py` | Bounded persistent Context LRU with resolved-path and file-signature invalidation |
| `query_service.py` | Catalog contracts, focus/device selection, executor reuse, completeness and timeout budget |
| `capability_service.py`, `overview_service.py` | Full catalog and read-only database/device/event-bound/import-metadata probes |
| `report_service.py` | Compose named queries into peak-memory reports rather than duplicate SQL |
| `import_service.py`, `import_metadata.py` | Trusted-input import validation, source/cache identity, metadata, optional focus |
| `snapshot_import_backend.py` | Runtime adapter, temporary database, publication and rollback resources |
| `split_service.py` | Strategy/device validation, staging, replay validation and exclusive directory publication |
| `skill_service.py` | Skill discovery, status, install/upgrade/uninstall destination policy |
| `models.py`, `errors.py` | Shared dataclass results and normalized domain failures |
| `error_codes.py`, `json_codec.py` | Stable JSON error classification/hints and serializable envelopes |
| `analysis/focus_service.py` | Resolve/validate database and device; explicit project/global focus writes |
| `cache/context_cache.py` | Bounded persistent Context LRU with resolved-path and file-signature invalidation |
| `analysis/query_service.py` | Catalog contracts, focus/device selection, executor reuse, completeness and timeout budget |
| `analysis/capability_service.py`, `analysis/overview_service.py` | Full catalog and read-only database/device/event-bound/import-metadata probes |
| `analysis/report_service.py` | Compose named queries into peak-memory reports rather than duplicate SQL |
| `importing/import_service.py`, `importing/import_metadata.py` | Trusted-input import validation, source/cache identity, metadata, optional focus |
| `importing/snapshot_import_backend.py` | Runtime adapter, temporary database, publication and rollback resources |
| `splitting/split_service.py` | Strategy/device validation, staging, replay validation and exclusive directory publication |
| `analysis/skill_service.py` | Skill discovery, status, install/upgrade/uninstall destination policy |
| `common/models.py`, `common/errors.py` | Shared dataclass results and normalized domain failures |
| `common/error_codes.py`, `common/json_codec.py` | Stable JSON error classification/hints and serializable envelopes |

## Ownership and Query Lifetime

Expand Down Expand Up @@ -75,6 +91,6 @@ concurrent destination creation must fail rather than replace another result.
Use [service tests](../../../tests/core/AGENTS.md) for the owning suite. Shared
result/error changes also require `tests/test_contract_cli_api.py` and JSON
contracts; template metadata must flow through `template_info_to_dict` to both
adapters. Keep the `models.py` Any/Unknown type gates intact. Runtime changes
adapters. Keep the `common/models.py` Any/Unknown type gates intact. Runtime changes
also follow [snapshot guidance](../snapshot/AGENTS.md), and skill content changes
follow [authoring/evaluation](../../../skills/AGENTS.md).
Loading
Loading