### Install pykissembed with uv Source: https://github.com/acoustesh/pykissembed/blob/main/tests/fixtures/sample_repo/MIGRATION_RUN.md Install the pykissembed package from a local directory using uv. The output shows it installed version 0.1.0. Required as step 1 of the migration recipe. ```text $ uv pip install -e /home/alvaro/pykissembed Installed 1 package in 1ms ~ pykissembed==0.1.0 (from file:///home/alvaro/pykissembed) ``` -------------------------------- ### Install cloud extra and configure provider API keys Source: https://github.com/acoustesh/pykissembed/blob/main/README.md Install the cloud extra and set environment variables for the providers you intend to populate. Only configure providers you explicitly plan to use. ```bash pip install "pykissembed[cloud]" export OPENAI_API_KEY=sk-... export OPENROUTER_API_KEY=sk-or-... export VOYAGE_API_KEY=pa-... export GOOGLE_API_KEY=... export JINA_API_KEY=jina_... ``` -------------------------------- ### Install pykissembed with uv Source: https://github.com/acoustesh/pykissembed/blob/main/README.md Install the pykissembed package using uv. ```bash uv add pykissembed ``` -------------------------------- ### pyproject.toml [tool.pykissembed] configuration example Source: https://github.com/acoustesh/pykissembed Example TOML block for configuring pykissembed in a consumer's pyproject.toml. Shows all available options with their defaults and usage. Note that invalid mode values silently fall back to "ratchet", and cache_dir is deprecated. ```toml [tool.pykissembed] paths = ["src", "scripts", "tests"] mode = "ratchet" baseline_dir = "tests/baselines" include_notebooks = false cached_only = true wrapper_max_call_sites = 1 wrapper_exclude = ["src/db.py:legacy_adapter"] wrapper_exempt_decorators = ["@pytest.fixture"] ``` -------------------------------- ### load_config(start: Path | None = None) -> PyqtestConfig Source: https://github.com/acoustesh/pykissembed Loads the resolved configuration by walking up from the given start directory (default current working directory) to find the first pyproject.toml. If none is found, falls back to auto-detection from layout conventions. ```APIDOC ## load_config(start: Path | None = None) -> PyqtestConfig ### Description Loads the resolved configuration by walking up from the given start directory (default current working directory) to find the first pyproject.toml. If none is found, falls back to auto-detection from layout conventions. ### Parameters - `start` (Path | None) - Optional - Starting directory for configuration discovery; defaults to current working directory. ### Returns - `PyqtestConfig` - The resolved configuration object. ### Raises - `FileNotFoundError` - If no pyproject.toml is found and auto-detection fails. - `TypeError` - If configuration values are of invalid types (e.g., `cached_only` not bool, `wrapper_max_call_sites` not non-negative int, `wrapper_exclude` not list of strings). ``` -------------------------------- ### Example: Using similarity analysis functions Source: https://github.com/acoustesh/pykissembed Loads minimal baselines, extracts functions with min_loc=1, fits PCA with a variance threshold of 0.99, and clusters functions. Prints cluster names and sizes. ```python from pykissembed.similarity import ( extract_all_function_infos, load_minimal_baselines, fit_pca, transform_embeddings_with_pca, cluster_functions_kmeans_with_pca, compute_similarity_matrix, compute_refactor_indices, ) baselines = load_minimal_baselines() functions = extract_all_function_infos(min_loc=1) model, n_components, is_gpu = fit_pca(baselines.get("openai_text_embeddings", {}), 0.99) if model is not None: transform_embeddings_with_pca(functions, model, n_components, is_gpu=is_gpu) clusters, names = cluster_functions_kmeans_with_pca(functions, model, n_components) print(names, [len(c) for c in clusters]) ``` -------------------------------- ### Install pykissembed-cloud with pip Source: https://github.com/acoustesh/pykissembed/blob/main/pykissembed_cloud/README.md Install the cloud embedding providers package via pip. ```bash pip install pykissembed-cloud ``` -------------------------------- ### Install pykissembed from TestPyPI and verify version Source: https://github.com/acoustesh/pykissembed/blob/main/README.md Installs the all extras from TestPyPI, updates the lock file for pykissembed packages, syncs dependencies, and checks the version (should show 0.3.4). ```bash uv add "pykissembed[all]" uv lock --upgrade-package pykissembed --upgrade-package pykissembed-cloud uv sync uv run pykissembed --version # should show 0.3.4 ``` -------------------------------- ### Extract function infos from configured directories Source: https://github.com/acoustesh/pykissembed Scans the first configured source directory with a minimum of 15 executable lines and prints the first three functions' name, file, start line, loc, and hash prefix. ```python from pathlib import Path from pykissembed.similarity import extract_function_infos, extract_all_function_infos # Scan the first configured source directory, minimum 15 executable lines fns = extract_function_infos(min_loc=15) for fn in fns[:3]: print(fn.name, fn.file, fn.start_line, fn.loc, fn.hash[:8]) ``` -------------------------------- ### ensure_loaded Source: https://github.com/acoustesh/pykissembed Loads the specified keys from a .env file once per starting directory. Subsequent calls with the same start are no-ops. Returns the path to the loaded file or None. ```APIDOC ## ensure_loaded ### Description Loads the specified keys from a .env file once per starting directory. Subsequent calls with the same start are no-ops. Returns the path to the loaded file or None. ### Signature `ensure_loaded(keys: tuple[str, ...] = ("OPENROUTER_API_KEY",), *, start: Path | None = None) -> Path | None` ### Parameters - `keys` (tuple[str, ...]) - Optional - Keys to load; defaults to ("OPENROUTER_API_KEY",). - `start` (Path | None) - Optional - Starting directory for .env search; defaults to current working directory. ### Returns - `Path | None` - Path to the loaded .env file, or None. ``` -------------------------------- ### get Source: https://github.com/acoustesh/pykissembed Convenience accessor: runs `discover_all()` once if the registry is empty, then returns `REGISTRY.get(name)`. ```APIDOC ## get ### Description Convenience accessor: runs `discover_all()` once if the registry is empty, then returns `REGISTRY.get(name)`. ### Method get ### Signature `(name: str) -> Provider | None` ### Parameters - **name** (str) - Required - The name of the provider to retrieve. ### Returns - **Provider | None** - The provider if found, otherwise None. ``` -------------------------------- ### Install pykissembed with pip Source: https://github.com/acoustesh/pykissembed/blob/main/README.md Install the pykissembed package using pip. ```bash pip install pykissembed ``` -------------------------------- ### Install pykissembed with GPU extra and CUDA 13 dependencies Source: https://github.com/acoustesh/pykissembed/blob/main/README.md Declares the GPU extra and installs all dependency groups and extras in a Python 3.14.6 environment. Uses the NVIDIA index for cuML CUDA 13 packages and verifies the installation. ```bash uv add --optional gpu \ --index nvidia=https://pypi.nvidia.com \ 'cuml-cu13==26.8.*' uv sync --all-groups --upgrade --all-extras .venv/bin/python -c "import cuml; print(cuml.__version__)" ``` -------------------------------- ### pytest invocation examples for pykissembed checks Source: https://github.com/acoustesh/pykissembed Shows how to invoke the pykissembed pytest plugin for different check categories. Use --pykissembed-all for the full battery, -m lint for lint/type/no-suppressions, -m complexity for complexity gates, -m similarity --cached-only for cache-only similarity, -m jev for Jev audits, and --update-baselines to seed baselines on a clean tree. ```python # Consumer invocation (not test code): # pytest --pykissembed-all full battery # pytest -m lint lint + type + no-suppressions # pytest -m complexity complexity gates # pytest -m similarity --cached-only similarity, cache-only # pytest -m jev Jev docstring + comment audits # pytest --pykissembed-all --update-baselines seed baselines on a clean tree ``` -------------------------------- ### Use pykissembed fixtures in own check module Source: https://github.com/acoustesh/pykissembed Example of using the `pykissembed_paths` and `update_baselines` fixtures in a custom check module. Skips the test if no `[tool.pykissembed]` paths are configured. ```python # Using the fixtures in your own check module import pytest @pytest.mark.complexity def test_my_gate(pykissembed_paths, update_baselines): if not pykissembed_paths: pytest.skip("No [tool.pykissembed] paths configured") assert update_baselines in (True, False) ``` -------------------------------- ### Iterate Python files with pykissembed.paths Source: https://github.com/acoustesh/pykissembed Loads configuration, resets the config cache, and iterates over Python files under the baseline path's parent. Files are sorted, and those starting with '__' or rejected by should_skip (hidden or ignored directories) are skipped. ```python from pykissembed.config import load_config, reset_config_cache from pykissembed.paths import resolve_paths, iter_py_files config = load_config() # resolves [tool.pykissembed] reset_config_cache() # force reload on next get_config() for py_file in iter_py_files(config.baseline_path.parent): print(py_file) # sorted, __*/ignored/hidden skipped ``` -------------------------------- ### Populate cloud embeddings for similarity test Source: https://github.com/acoustesh/pykissembed/blob/main/tests/fixtures/sample_repo/MIGRATION_RUN.md Populate a cloud embedding provider explicitly for the similarity test. This installs the cloud extra, sets an OpenRouter API key, runs populate-embeddings with the qwen-text provider, then runs the similarity-tagged tests. Population transmits code-derived text or normalized AST to the selected service and may incur API charges; a normal pytest run never does this while cached_only is true. ```text uv pip install -e /home/alvaro/pykissembed/pykissembed_cloud export OPENROUTER_API_KEY=sk-or-... pykissembed populate-embeddings --provider qwen-text pytest -m similarity ``` -------------------------------- ### Justified absence penalty example (regex loop) Source: https://github.com/acoustesh/pykissembed/blob/main/docs/plans/jev-cache.md Worked example stored as `_ABSENCE_EXAMPLE` and appended verbatim to rule 2. It illustrates when a missing comment is penalized (Moderate, level 1) versus when it is not (level 4). The regex removes only innermost parenthesised groups, so the loop must repeat until nothing changes; a single `.sub()` would leave nested groups. The comment belongs at the guard, not in the docstring. ```python _TOKEN = re.compile( r"""(?P"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')""" r"""|\((?:[^()'"]|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')*\)""" ) while True: updated = _TOKEN.sub( lambda m: m.group(0) if m.group("quoted") is not None else "", text, ) if updated == text: return text text = updated ``` -------------------------------- ### discover_builtin Source: https://github.com/acoustesh/pykissembed Registers providers bundled with core. Core currently bundles no embedding provider (network-neutral install); the hook is kept for compatibility. ```APIDOC ## discover_builtin ### Description Registers providers bundled with core. Core currently bundles no embedding provider (network-neutral install); the hook is kept for compatibility. ### Method discover_builtin ### Signature `() -> None` ### Returns None ``` -------------------------------- ### find_dotenv Source: https://github.com/acoustesh/pykissembed Walks up from a starting directory to find the first .env file. Returns the path to the .env file or None if not found. ```APIDOC ## find_dotenv ### Description Walks up from a starting directory to find the first .env file. Returns the path to the .env file or None if not found. ### Signature `find_dotenv(start: Path | None = None) -> Path | None` ### Parameters - `start` (Path | None) - Optional - Starting directory; defaults to current working directory. ### Returns - `Path | None` - Path to the first .env file found, or None. ``` -------------------------------- ### should_skip(path: Path, base: Path) -> bool Source: https://github.com/acoustesh/pykissembed Determines whether a path should be skipped based on ignored directories or hidden directories. Returns True when any directory between base and path (exclusive of path itself) is in _IGNORED_DIRS or starts with a dot. ```APIDOC ## should_skip(path: Path, base: Path) -> bool ### Description True when any directory between `base` and `path` (exclusive of `path` itself) is in `_IGNORED_DIRS` or starts with `.` (hidden). ### Parameters - **path** (Path) - Required - The path to check. - **base** (Path) - Required - The base directory to start checking from. ### Returns - **bool** - True if the path should be skipped, False otherwise. ``` -------------------------------- ### Run JEV tests and repo gates Source: https://github.com/acoustesh/pykissembed/blob/main/docs/plans/jev-cache.md Verification step 1: sync all extras and run the JEV and plugin collection tests. Step 2: run the repo's own gates (ruff, pyright/ty, test_no_suppressions_or_casts, similarity). If the Qwen-AST gate fails, A/B it against a stash because three near-duplicate pairs are already known to fail on main. ```bash uv sync --all-extras, then `uv run pytest tests/test_jev_*.py tests/test_plugin_collection.py`. ``` -------------------------------- ### CLI commands overview Source: https://github.com/acoustesh/pykissembed/blob/main/README.md Lists the main pykissembed CLI commands: check, ratchet, providers list, populate-embeddings, type-review, and init. The init command optionally scaffolds configuration and syncs VS Code settings. ```text pykissembed check # run the same gate pytest runs pykissembed ratchet # lower baselines; refuse to raise pykissembed providers list # show installed embedding providers pykissembed populate-embeddings --provider NAME pykissembed type-review --json REPORT.json # iterative type-fix helper pykissembed init # (opt-in) scaffold [tool.pykissembed] and sync .vscode/settings.json ``` -------------------------------- ### List baseline files in tests/baselines/ Source: https://github.com/acoustesh/pykissembed/blob/main/tests/fixtures/sample_repo/MIGRATION_RUN.md List the baseline fixture files that already exist before migration steps run. The source shows this in the Pre-conditions section to confirm the fixture is at v1 envelopes. ```text $ ls tests/baselines/ comment_density.json complexity.json docstring_format.json ``` -------------------------------- ### discover_all Source: https://github.com/acoustesh/pykissembed Runs `discover_builtin()` then `REGISTRY.discover()`; returns `REGISTRY`. ```APIDOC ## discover_all ### Description Runs `discover_builtin()` then `REGISTRY.discover()`; returns `REGISTRY`. ### Method discover_all ### Signature `() -> ProviderRegistry` ### Returns - **ProviderRegistry** - The global registry after discovery. ``` -------------------------------- ### pykissembed init [--force] Source: https://github.com/acoustesh/pykissembed Scaffolds or merges the [tool.pykissembed] configuration block into pyproject.toml and syncs .vscode/settings.json. Exits with code 1 if no pyproject.toml exists. ```APIDOC ## pykissembed init [--force] ### Description Scaffolds/merges `[tool.pykissembed]` into `pyproject.toml` (path auto-detection: `[tool.setuptools.packages.find] where` → Hatch wheel `packages` roots → `src/` → `.`), then syncs `.vscode/settings.json` via `vscode_settings.sync_vscode_settings`. `typer.Exit(1)` when no `pyproject.toml` exists. ### Method CLI command ### Command `pykissembed init [--force]` ### Parameters #### Options - `--force` (bool) - Optional - Overwrite an existing `[tool.pykissembed]` block and any conflicting `.vscode/settings.json` pytest values. ### Response #### Exit Codes - `0` - Success - `1` - No `pyproject.toml` exists ### Generated Block ```toml [tool.pykissembed] paths = ["src"] mode = "ratchet" baseline_dir = "tests/baselines" # cached_only = true (only when the existing block had cached_only set) ``` ``` -------------------------------- ### build_report(ruff_diags, pyright_diags, root: Path) Source: https://github.com/acoustesh/pykissembed Builds a report dictionary containing per-file diagnostics and a summary of counts. The report includes files mapped to their ruff and pyright diagnostics, and a summary with total counts. ```APIDOC ## build_report(ruff_diags, pyright_diags, root: Path) ### Description Builds a report dictionary with per-file diagnostics and a summary. The `files` key maps relative paths to objects containing `ruff` and `pyright` diagnostic lists. The `summary` key contains total counts. ### Method Function call ### Signature `build_report(ruff_diags, pyright_diags, root: Path) -> dict[str, Any]` ### Parameters - **ruff_diags** - Required - Ruff diagnostics. - **pyright_diags** - Required - Pyright diagnostics. - **root** (Path) - Required - Root path for resolving relative file paths. ### Returns - **dict[str, Any]** - Report with `files` and `summary` keys. ``` -------------------------------- ### reset_cache_for Source: https://github.com/acoustesh/pykissembed Clears the cache entry for a specific starting directory. ```APIDOC ## reset_cache_for ### Description Clears the cache entry for a specific starting directory. ### Signature `reset_cache_for(start: Path | None) -> None` ### Parameters - `start` (Path | None) - Required - The starting directory whose cache entry to clear. ``` -------------------------------- ### Handle broken entry points during discovery Source: https://github.com/acoustesh/pykissembed Shows that discover_all() internally warns and skips bad entry points instead of aborting. Captures RuntimeWarning messages to observe the failure. ```python # Error handling: a broken third-party entry point never aborts discovery import warnings from pykissembed.providers import discover_all with warnings.catch_warnings(record=True) as caught: warnings.simplefilter("always") registry = discover_all() # internally warns + skips bad entry points for w in caught: if issubclass(w.category, RuntimeWarning): print(w.message) # "pykissembed: failed to load provider entry point ..." ``` -------------------------------- ### Live JEV cache check with OPENROUTER_API_KEY Source: https://github.com/acoustesh/pykissembed/blob/main/docs/plans/jev-cache.md Verification step 3: requires OPENROUTER_API_KEY. Run the JEV-marked tests twice without cache. Run 1 fills jev_cache.sqlite3; record the row count with the sqlite3 query. Run 2 should finish in seconds with the row count unchanged. Editing one comment and rerunning should add exactly one new row. ```bash uv run pytest -m jev pykissembed/checks -p no:cacheprovider ``` ```bash sqlite3 … 'select count(*) from jev_responses' ``` -------------------------------- ### Run live smoke tests Source: https://github.com/acoustesh/pykissembed/blob/main/README.md Opt-in command to run cloud smoke calls against fixed synthetic strings. Live network tests are skipped by default. ```bash # Run cloud smoke calls against fixed synthetic strings uv run pytest -m "live and smoke" ``` -------------------------------- ### Configure provider keys and pre-warm embeddings Source: https://github.com/acoustesh/pykissembed/blob/main/README.md Sets OpenRouter and Jina API keys (or uses a .env file), then explicitly pre-warms canonical text/AST caches before running the similarity test suite. Missing embeddings remain offline by default; population is an explicit pre-warming step. ```bash # Entry-point openai/gemini/qwen providers use OpenRouter; fixed similarity # variants preserve their documented native/OpenRouter credentials. export OPENROUTER_API_KEY=sk-or-... export JINA_API_KEY=jina_... # ... or drop the keys into a .env file at the project root # Explicitly pre-warm canonical text/AST caches pykissembed populate-embeddings --provider qwen-text pykissembed populate-embeddings --provider jina-ast pytest -m similarity ``` -------------------------------- ### load_all_complexity_maps() Source: https://github.com/acoustesh/pykissembed Recursive scan of every configured directory with project-relative prefixes (`"{rel_dir}/{function_name}"` keys). ```APIDOC ## load_all_complexity_maps() -> tuple[dict[str, int], dict[str, int]] ### Description Recursive scan of every configured directory with project-relative prefixes (`"{rel_dir}/{function_name}"` keys). ### Returns - **tuple[dict[str, int], dict[str, int]]** - A tuple of two dictionaries: CC map and COG map. ``` -------------------------------- ### Use pykissembed CLI commands Source: https://github.com/acoustesh/pykissembed/blob/main/pykissembed_cloud/README.md Commands to list providers, populate embeddings with canonical variants, and run similarity tests. The population command uses canonical text/AST variants rather than short entry-point names. Calls may incur API charges. ```bash pykissembed providers list # confirms registration pykissembed populate-embeddings --provider gemini-text pykissembed populate-embeddings --provider jina-ast pytest -m similarity ``` -------------------------------- ### iter_py_files(base_dir: Path) -> Iterator[Path] Source: https://github.com/acoustesh/pykissembed Yields every Python file under the given base directory recursively, sorted for determinism. Skips files whose name starts with double underscores and anything that should_skip rejects. ```APIDOC ## iter_py_files(base_dir: Path) -> Iterator[Path] ### Description Yields every `*.py` under `base_dir` recursively, sorted for determinism; skips files whose name starts with `__` and anything `should_skip` rejects. ### Parameters - **base_dir** (Path) - Required - The directory to search for Python files. ### Returns - **Iterator[Path]** - An iterator of Python file paths. ``` -------------------------------- ### Baseline-and-ratchet workflow commands Source: https://github.com/acoustesh/pykissembed/blob/main/README.md Commands for seeding baselines, running tests, ratcheting baselines, and discovering the JSON schema. Use the first command on an existing codebase to seed baselines; subsequent commands are for day-to-day regression testing and periodic ratcheting. ```bash # 1. First time on an existing codebase — seed baselines pytest --pykissembed-all --update-baselines git add tests/baselines && git commit -m "seed pykissembed baselines" # 2. Day-to-day — fix code; tests only fail on REGRESSIONS pytest --pykissembed-all # any diagnostic above its baseline fails the build # 3. Periodic ratchet — lower baselines as you fix issues pykissembed ratchet # scans tests/baselines/*.json for ratchetable data # 4. Discover the JSON schema for a baseline type pykissembed schema --kind complexity ``` -------------------------------- ### run_ruff(paths: list[Path]) Source: https://github.com/acoustesh/pykissembed Runs the ruff linter on the given paths and returns diagnostics in JSON format. Excludes .ipynb files unless include_notebooks is set, and returns an empty list on subprocess error or timeout. ```APIDOC ## run_ruff(paths: list[Path]) ### Description Runs `ruff check --preview --output-format json` on the given paths and returns the diagnostics. Excludes `.ipynb` files unless `include_notebooks` is set. Returns an empty list on subprocess error or timeout (120s). ### Method Function call ### Signature `run_ruff(paths: list[Path]) -> list[Mapping[str, object]]` ### Parameters - **paths** (list[Path]) - Required - List of file or directory paths to lint. ### Returns - **list[Mapping[str, object]]** - List of ruff diagnostics in JSON format. ``` -------------------------------- ### ProviderRegistry.discover Source: https://github.com/acoustesh/pykissembed Loads entry points from group `pykissembed.providers` in reverse order (first-listed wins). A broken entry point (import/instantiation failure) warns `RuntimeWarning` and is skipped; a class-typed value is instantiated. ```APIDOC ## ProviderRegistry.discover ### Description Loads entry points from group `pykissembed.providers` in reverse order (first-listed wins). A broken entry point (import/instantiation failure) warns `RuntimeWarning` and is skipped; a class-typed value is instantiated. ### Method discover ### Signature `() -> None` ### Returns None ``` -------------------------------- ### Handle invalid config values with TypeError Source: https://github.com/acoustesh/pykissembed Shows error handling when load_config encounters an invalid configuration value. For example, if pyproject.toml contains 'wrapper_max_call_sites = false', load_config raises TypeError with the message "[tool.pykissembed] 'wrapper_max_call_sites' must be a non-negative integer". ```python # Error-handling example: invalid config values raise TypeError import tomllib from pathlib import Path from pykissembed.config import load_config # Given a pyproject.toml containing wrapper_max_call_sites = false, # load_config raises TypeError("[tool.pykissembed] 'wrapper_max_call_sites' must be a non-negative integer") try: load_config(Path.cwd()) except TypeError as exc: print(f"config error: {exc}") ``` -------------------------------- ### Get embeddings and compute cosine similarity Source: https://github.com/acoustesh/pykissembed Fetches embeddings for a batch of texts using the specified provider and model, then computes cosine similarity between the first two vectors. Retries each batch up to max_retries times with [1.0, 2.0, 4.0] backoff when is_retryable(exc) is true; last failure is re-raised. ```python from pykissembed.similarity import ( get_embeddings_batch, compute_cosine_similarity, compute_combined_embedding, ) vecs = get_embeddings_batch( ["def f(): pass", "def g(): pass"], provider="openai", model="text-embedding-3-large", max_retries=3, ) print(compute_cosine_similarity(vecs[0], vecs[1])) ``` -------------------------------- ### Run pykissembed ratchet Source: https://github.com/acoustesh/pykissembed/blob/main/tests/fixtures/sample_repo/MIGRATION_RUN.md Run pykissembed ratchet to lower baselines. The output shows three expected skips for baseline files without current-diagnostics computers; only lint_typecheck.json has one. The command completes without lowering any baselines. ```text $ pykissembed ratchet skip comment_density.json: no current-diagnostics computer implemented skip complexity.json: no current-diagnostics computer implemented skip docstring_format.json: no current-diagnostics computer implemented Done. 0 baseline file(s) lowered. ``` -------------------------------- ### Populate embeddings with pykissembed Source: https://github.com/acoustesh/pykissembed Shows how to pre-warm a canonical cache, inspect coverage without network, and use a populator directly. Requires OPENAI_API_KEY or .env for network calls; cached_only=True prints missing counts per provider. ```python from pykissembed.similarity.populate_embeddings import ( populate_provider_embeddings, get_provider_populator, PopulationError, ) # Pre-warm one canonical cache (needs OPENAI_API_KEY / .env) populate_provider_embeddings("openai-text") # Inspect coverage without network: prints missing counts per provider populate_provider_embeddings("all", cached_only=True) # Use the populator directly inside another tool fn = get_provider_populator("jina-ast") if fn is not None: new = fn(baselines, functions) # -> int new embeddings ``` -------------------------------- ### Opt in to Jupyter notebook checks Source: https://github.com/acoustesh/pykissembed/blob/main/README.md Configuration to enable ruff and similarity checks on .ipynb files. By default, notebooks are excluded because they typically contain exploratory code with relaxed hygiene. ```toml [tool.pykissembed] include_notebooks = true # apply ruff + similarity to .ipynb too ``` -------------------------------- ### Create Typer app with no_args_is_help and rich markup Source: https://github.com/acoustesh/pykissembed Defines the `pykissembed` Typer app with `no_args_is_help=True` and `rich_markup_mode='rich'`. This is the console script entry point (`pykissembed` → `pykissembed.cli:app`). ```python app = typer.Typer( name="pykissembed", help="Generic Python code-quality test library (pytest plugin).", no_args_is_help=True, rich_markup_mode="rich", ) ``` -------------------------------- ### Grep for [tool.pykissembed] in pyproject.toml Source: https://github.com/acoustesh/pykissembed/blob/main/tests/fixtures/sample_repo/MIGRATION_RUN.md Check that the [tool.pykissembed] configuration exists in pyproject.toml. The output shows the declared settings: paths set to src, mode ratchet, baseline_dir tests/baselines, and cached_only true. ```text $ grep -A4 tool.pykissembed pyproject.toml [tool.pykissembed] paths = ["src"] mode = "ratchet" baseline_dir = "tests/baselines" cached_only = true ``` -------------------------------- ### run_pyright(paths: list[Path]) Source: https://github.com/acoustesh/pykissembed Runs the Pyright type checker on the given paths and returns general diagnostics. Returns an empty list on failure. ```APIDOC ## run_pyright(paths: list[Path]) ### Description Runs `pyright --outputjson` on the given paths and returns the `generalDiagnostics`. Returns an empty list on failure. ### Method Function call ### Signature `run_pyright(paths: list[Path]) -> list[Mapping[str, object]]` ### Parameters - **paths** (list[Path]) - Required - List of file or directory paths to type-check. ### Returns - **list[Mapping[str, object]]** - List of Pyright general diagnostics. ``` -------------------------------- ### pykissembed docfix [PATHS...] [options] Source: https://github.com/acoustesh/pykissembed Builds a docfix.Request and calls tool.docfix.main to run documentation fixes. Exits with 0 on success, 1 on file errors or pending fixes under --check, and 2 on invalid arguments. ```APIDOC ## pykissembed docfix [PATHS...] [options] ### Description Builds a `docfix.Request` (model falls back to `tool.docfix.DEFAULT_MODEL` = `"@preset/deepseek"`) and calls `tool.docfix.main`. Exits: `0` success; `1` file errors or pending fixes under `--check`; `2` invalid arguments (unknown DF code, malformed `--symbol`, or `--draft`/`--grade` without `OPENROUTER_API_KEY`). ### Method CLI command ### Command `pykissembed docfix [PATHS...] [options]` ### Parameters #### Arguments - `PATHS...` (list[Path]) - Optional - Paths to process. #### Options - `--write` (bool) - Optional - Write changes. - `--diff` (bool) - Optional - Show diff. - `--check` (bool) - Optional - Check mode; exit 1 if pending fixes. - `--select` (str) - Optional - Comma-separated DF codes; `DF052` is opt-in. - `--ignore` (str) - Optional - DF codes to ignore. - `--symbol` (list[str]) - Optional - Repeatable; format `FILE::NAME`. - `--only-failing` (bool) - Optional - Only process failing items. - `--allow-dirty` (bool) - Optional - Allow dirty working tree. - `--draft` (bool) - Optional - Use OpenRouter drafting. - `--grade` (bool) - Optional - Revert Jev-level regressions. - `--model` (str) - Optional - Model to use. - `--max-calls` (int) - Optional - Default 50. - `--line-length` (int) - Optional - Default 88. - `--grade-tolerance` (float) - Optional - Default 0.1. ### Response #### Exit Codes - `0` - Success - `1` - File errors or pending fixes under `--check` - `2` - Invalid arguments (unknown DF code, malformed `--symbol`, or `--draft`/`--grade` without `OPENROUTER_API_KEY`) ``` -------------------------------- ### Run pytest --update-baselines in sample_repo Source: https://github.com/acoustesh/pykissembed/blob/main/tests/fixtures/sample_repo/MIGRATION_RUN.md Run pytest with --update-baselines inside the fixture directory to seed and verify baselines. The output shows 1 passed and 10 skipped, where the skips are pykissembed's own gate tests that update baselines then skip (documented update-mode behaviour). ```text $ cd tests/fixtures/sample_repo $ /home/alvaro/pykissembed/.venv/bin/pytest tests/ --update-baselines … ======================== 1 passed, 10 skipped in 0.41s ========================= ``` -------------------------------- ### run Source: https://github.com/acoustesh/pykissembed Runs the docfix engine over the given paths with the provided options. Returns a list of FileResult objects. ```APIDOC ## run ### Description Runs the docfix engine over the given paths with the provided options. Returns a list of FileResult objects. ### Method Function call ### Signature `run(request: Request) -> list[FileResult]` ### Parameters - **request** (Request) - Required - The request configuration specifying paths and options. ### Returns - **list[FileResult]** - A list of results for each processed file. ``` -------------------------------- ### Seed pykissembed baselines Source: https://github.com/acoustesh/pykissembed/blob/main/README.md Write baselines equal to current diagnostics on a clean tree, then commit them so CI doesn't fail before fixes. ```bash pytest --pykissembed-all --update-baselines # write baselines = current diagnostics git add tests/baselines && git commit -m "seed pykissembed baselines" ``` -------------------------------- ### Populate embeddings for selected providers Source: https://github.com/acoustesh/pykissembed/blob/main/README.md Explicitly populate only the selected cache. The 'all' provider must be requested explicitly. ```bash pykissembed populate-embeddings --provider openai-text pykissembed populate-embeddings --provider openai-ast # "all" must be requested explicitly pykissembed populate-embeddings --provider all ``` -------------------------------- ### Run provider similarity checks with OpenAI Text provider Source: https://github.com/acoustesh/pykissembed Loads minimal baselines and all function infos, then runs provider similarity checks with cached-only mode to avoid network calls. Uses OPENAI_TEXT_PROVIDER with pair threshold 0.86 and neighbor threshold 0.80. ```python from pykissembed.similarity import ( OPENAI_TEXT_PROVIDER, run_provider_similarity_checks, extract_all_function_infos, load_minimal_baselines, ) from pykissembed.similarity.complexity import load_all_complexity_maps baselines = load_minimal_baselines() functions = extract_all_function_infos(min_loc=1) run_provider_similarity_checks( baselines=baselines, functions=functions, update_baselines=False, cached_only=True, # never phone home provider=OPENAI_TEXT_PROVIDER, threshold_pair=0.86, threshold_neighbor=0.80, load_complexity_maps_fn=load_all_complexity_maps, ) ``` -------------------------------- ### load_complexity_maps(directory) Source: https://github.com/acoustesh/pykissembed Loads CC and COG maps for one directory (default: first configured path); shallow scan; returns ({}, {}) when no paths are configured. ```APIDOC ## load_complexity_maps(directory: Path | None = None) -> tuple[dict[str, int], dict[str, int]] ### Description Loads CC and COG maps for one directory (default: first configured path); shallow scan; returns `({}, {})` when no paths are configured. ### Parameters - **directory** (Path | None) - Optional - The directory to scan. Defaults to the first configured path. ### Returns - **tuple[dict[str, int], dict[str, int]]** - A tuple of two dictionaries: CC map and COG map. ``` -------------------------------- ### root() -> Path Source: https://github.com/acoustesh/pykissembed Returns the root path from the configuration. ```APIDOC ## root() -> Path ### Description `get_config().root`. ### Returns - **Path** - The root path. ``` -------------------------------- ### pykissembed --version Source: https://github.com/acoustesh/pykissembed Prints the pykissembed version and exits. ```APIDOC ## pykissembed --version ### Description Prints the pykissembed version and exits. ### Method CLI ### Endpoint `pykissembed --version` ### Parameters None ### Response Prints `pykissembed {__version__}` and exits with status 0. ``` -------------------------------- ### Run full battery or single check class Source: https://github.com/acoustesh/pykissembed Shows how to run the full battery of checks with `pytest --pykissembed-all` or a single check class, e.g., `TestCyclomaticComplexity`. ```python # A consumer runs the full battery: # pytest --pykissembed-all # Or a single check class: # pytest .../pykissembed/checks/code_complexity.py::TestCyclomaticComplexity ``` -------------------------------- ### populate_embeddings(provider: str = "all") -> None Source: https://github.com/acoustesh/pykissembed Backwards-compatible wrapper calling populate_provider_embeddings(provider). ```APIDOC ## populate_embeddings(provider: str = "all") -> None ### Description Backwards-compatible wrapper calling `populate_provider_embeddings(provider)`. ### Parameters - `provider` (str) - Optional - Default: `"all"` - Provider name. ``` -------------------------------- ### load_api_key_from_env(env_var, *, invalid_prefixes, min_length) Source: https://github.com/acoustesh/pykissembed Loads an API key from an environment variable or a .env file. Returns None if the key is invalid based on prefix or length constraints. ```APIDOC ## load_api_key_from_env(env_var: str, *, invalid_prefixes: tuple[str, ...] = (), min_length: int = 0) -> str | None ### Description Loads an API key from an environment variable or a .env file. Returns None if the key is invalid based on prefix or length constraints. ### Parameters #### Path Parameters - **env_var** (str) - Required - Environment variable name #### Query Parameters - **invalid_prefixes** (tuple[str, ...]) - Optional - Prefixes that make the key invalid (default: `()`) - **min_length** (int) - Optional - Minimum key length (default: `0`) ### Response #### Success Response (200) - Returns the API key as `str`, or `None` if not found or invalid ``` -------------------------------- ### pykissembed.tools.docfix.main Source: https://github.com/acoustesh/pykissembed Main entry point for the docfix tool. Runs the docfix process. ```APIDOC ## main ### Description Main entry point for the docfix tool. Runs the docfix process. ### Signature `main()` ``` -------------------------------- ### Run pytest in sample_repo after seeding Source: https://github.com/acoustesh/pykissembed/blob/main/tests/fixtures/sample_repo/MIGRATION_RUN.md Run pytest without update mode to verify the seeded baselines. The output shows 10 passed and 1 skipped; the skip is the similarity test which requires cloud embedding caches. ```text $ /home/alvaro/pykissembed/.venv/bin/pytest tests/ … ======================== 10 passed, 1 skipped in 0.39s ========================= ``` -------------------------------- ### pykissembed init function signature Source: https://github.com/acoustesh/pykissembed Signature for the `pykissembed init` command. Scaffolds/merges `[tool.pykissembed]` into `pyproject.toml` and syncs `.vscode/settings.json`. Exits with `typer.Exit(1)` when no `pyproject.toml` exists. ```python def init( *, force: Annotated[ bool, typer.Option("--force", help="Overwrite an existing [tool.pykissembed] block and any conflicting .vscode/settings.json pytest values."), ] = False, ) -> None ``` -------------------------------- ### Re-exports from pykissembed.providers __init__.py Source: https://github.com/acoustesh/pykissembed Shows the public API re-exported by the package's __init__.py. Use this to import Provider, REGISTRY, and ProviderRegistry directly from pykissembed.providers. ```python from pykissembed.providers.base import Provider from pykissembed.providers.registry import REGISTRY, ProviderRegistry __all__ = ["REGISTRY", "Provider", "ProviderRegistry"] ``` -------------------------------- ### pykissembed.tools.docfix.run Source: https://github.com/acoustesh/pykissembed Runs the docfix process programmatically. ```APIDOC ## run ### Description Runs the docfix process programmatically. ### Signature `run()` ``` -------------------------------- ### Custom provider implementation Source: https://github.com/acoustesh/pykissembed/blob/main/README.md Implements the Provider Protocol with required attributes (name, model_id, schema_version, max_tokens, batch_size) and methods embed and is_configured. The embed method returns a list of float vectors for each input text. ```python # my_pkg/providers.py from collections.abc import Sequence class MyProvider: name = "my_embedder" model_id = "my-model-v1" schema_version = "1" max_tokens = 512 batch_size = 32 def embed(self, texts: Sequence[str]) -> list[list[float]]: return [self._embed_one(t) for t in texts] def is_configured(self) -> bool: return True ``` -------------------------------- ### include_notebooks() -> bool Source: https://github.com/acoustesh/pykissembed Returns whether notebooks should be included from the configuration. ```APIDOC ## include_notebooks() -> bool ### Description `get_config().include_notebooks`. ### Returns - **bool** - True if notebooks should be included, False otherwise. ``` -------------------------------- ### extract_function_infos(min_loc=15, directory=None, *, file_prefix="", exclude_prefixes=(), recursive=False) Source: https://github.com/acoustesh/pykissembed Extracts FunctionInfo records from Python source files in a directory. Skips __init__ methods and __-prefixed files; @overload stubs are not skipped here. ```APIDOC ## extract_function_infos(min_loc=15, directory=None, *, file_prefix="", exclude_prefixes=(), recursive=False) ### Description Extracts FunctionInfo records from Python source files in a directory. Skips __init__ methods and __-prefixed files; @overload stubs are not skipped here. ### Parameters - **min_loc** (int) - Optional - Default: 15 - Minimum executable lines (docstring/comment/blank excluded) for inclusion. - **directory** (Path | None) - Optional - Default: None - Target directory; None uses the first resolved path. - **file_prefix** (str) - Optional - Default: "" - Prefix prepended to each file's display name (e.g. "src/"). - **exclude_prefixes** (tuple[str, ...]) - Optional - Default: () - Skip files whose name starts with any of these. - **recursive** (bool) - Optional - Default: False - If True, use rglob and subdirectory-prefixed display names. ### Returns - **list[FunctionInfo]** - List of extracted FunctionInfo records. ``` -------------------------------- ### Export API keys for cloud embedding routes Source: https://github.com/acoustesh/pykissembed/blob/main/pykissembed_cloud/README.md Export only the credentials for the routes you intend to use. The explicit environment variable always wins over a .env file. The loader runs lazily on the first is_configured() call. ```bash export OPENAI_API_KEY=sk-... # canonical openai-* similarity caches export GOOGLE_API_KEY=... # canonical gemini-* similarity caches export OPENROUTER_API_KEY=sk-or-... # entry points; canonical codestral-* and qwen-* export VOYAGE_API_KEY=pa-... # canonical voyage-* similarity caches export JINA_API_KEY=jina_... # entry point and canonical jina-* caches ``` -------------------------------- ### pykissembed.config.get_config Source: https://github.com/acoustesh/pykissembed Retrieves the current configuration, loading it if necessary. ```APIDOC ## get_config ### Description Retrieves the current configuration, loading it if necessary. ### Signature `get_config()` ### Returns - `PyqtestConfig` - The current configuration. ``` -------------------------------- ### extract_all_function_infos(min_loc=15) Source: https://github.com/acoustesh/pykissembed Scans every directory from paths.resolve_paths() recursively via extract_function_infos_from_directories. ```APIDOC ## extract_all_function_infos(min_loc=15) ### Description Scans every directory from paths.resolve_paths() recursively via extract_function_infos_from_directories. ### Parameters - **min_loc** (int) - Optional - Default: 15 - Minimum executable lines for inclusion. ### Returns - **list[FunctionInfo]** - List of extracted FunctionInfo records. ``` -------------------------------- ### Register provider entry point in pyproject.toml Source: https://github.com/acoustesh/pykissembed Consumers/libraries register providers in their own pyproject.toml using the [project.entry-points.pykissembed.providers] table. The key is the provider name and the value points to the provider class. ```toml [project.entry-points.pykissembed.providers] my_embedder = "my_pkg.providers:MyProvider" ``` -------------------------------- ### providers list command signature Source: https://github.com/acoustesh/pykissembed Signature for the `pykissembed providers list` command. Discovers providers and renders a rich table. ```python def providers_list() -> None ```