# Pluvy > Pluvy is a read-only, parser-backed engineering policy gate for Python, Go, Java, JavaScript/JSX, TypeScript/TSX, and Rust. It checks code written by people and coding agents against a repository's committed `.pluvy/pluvy.json` policy and fails the check when a change erases type contracts, suppresses diagnostics, swallows errors, weakens or deletes tests, or crosses declared architecture boundaries. Key CLI facts: - Modes (mutually exclusive): `pluvy --all`, `pluvy --base `, `pluvy --staged` - Options: `--root ` (default `.`), `--config ` (default `.pluvy/pluvy.json`), `--format text|json` - Exit codes: `0` pass (warnings allowed), `1` error findings present, `2` configuration/filesystem/Git failure - Read-only guarantee: Pluvy never edits, stages, stashes, restores, or deletes files, and never modifies Git configuration. ## Complete corpus - [Full documentation (single file)](https://sectrend-cn.github.io/pluvy/llms-full.txt): Plain-text bundle of all Pluvy documentation, sample policy, and bundled agent skill. ## Documentation (Markdown) - [getting-started](https://sectrend-cn.github.io/pluvy/docs/getting-started.md): Install Pluvy, bootstrap .pluvy/pluvy.json, run --all / --base / --staged, triage findings, and connect coding agents. - [checker-configuration](https://sectrend-cn.github.io/pluvy/docs/checker-configuration.md): Policy schema, all 22 built-in checkers and 29 diagnostic IDs, per-language coverage, deletion gate, and source placement. - [serialization-boundaries](https://sectrend-cn.github.io/pluvy/docs/serialization-boundaries.md): Directional third_party_modules boundaries, cross-file usage resolution, built-in JSON serializers, and type.broad.encoding options. - [comment-suppressions](https://sectrend-cn.github.io/pluvy/docs/comment-suppressions.md): Syntax, human-approval requirements, and validation rules for next-line diagnostic exceptions across all supported languages. - [engineering-standards](https://sectrend-cn.github.io/pluvy/docs/engineering-standards.md): Shared engineering policy and the division between automated Pluvy checks and code-review obligations. - [plugin-architecture](https://sectrend-cn.github.io/pluvy/docs/plugin-architecture.md): Decoupled tree-sitter language adapters, rule bundles, changed-scope filtering, and checker-owned registration. - [go-consumed-fields](https://sectrend-cn.github.io/pluvy/docs/go-consumed-fields.md): How Go usage analysis recognizes implicit struct field reads in serialization, reflect.DeepEqual, and structural equality. ## Agent skill & sample policy - [Agent skill (SKILL.md)](https://github.com/sectrend-cn/pluvy/blob/main/.agents/skills/pluvy/SKILL.md): Post-task gate workflow, command selection table, triage rules, and per-language checker matrix. - [Checker index](https://github.com/sectrend-cn/pluvy/blob/main/.agents/skills/pluvy/references/checkers.md): Per-checker option and diagnostic reference pages. - [Example policy](https://github.com/sectrend-cn/pluvy/blob/main/examples/.pluvy/pluvy.json): Starter .pluvy/pluvy.json declaring owners, import boundaries, encoding rules, and function limits. ## Blog - [Why Existing Tools Miss Agent Shortcuts](https://sectrend-cn.github.io/pluvy/blog/why-existing-tools-miss-agent-shortcuts/): Tests, type checkers and linters all pass a change that deletes a test, widens a signature to Any and swallows the error. Here is why, and what a gate has to do differently. --- Source: https://sectrend-cn.github.io/pluvy/docs/getting-started.md # Pluvy getting started This guide is for developers adopting Pluvy. It covers installing the CLI, configuring a policy for a target repository, running day-to-day checks, triaging existing findings, and running the gate after every code task. Pluvy is a read-only, parser-backed engineering policy gate: no run mode modifies, stages, restores, deletes or rewrites source files, and none of them changes Git configuration. ## Quick start From the root of the Git repository you want to check: ```sh uv tool install pluvy mkdir -p .pluvy echo '{"version": 2, "include": ["src/*", "tests/*"], "checkers": {}}' > .pluvy/pluvy.json pluvy --all ``` The output lists one finding per line, then a summary. For a `src/app.py` that declares `def load(value: Any) -> Any` and a test that calls `load(1)` and then asserts `True`: ```text src/app.py:4:17: type.annotation: Preserve a concrete contract instead of Any src/app.py:4:17: type.broad: Do not erase contracts with typing.Any src/app.py:4:25: type.annotation: Preserve a concrete contract instead of Any src/app.py:4:25: type.broad: Do not erase contracts with typing.Any tests/test_app.py:5:5: warning: unused.return: Return value from 'load' is discarded tests/test_app.py:6:5: test.tautology: Assertion in test_load cannot fail because it restates the same expression or a literal true. Assert an independently produced value or outcome instead. Diagnostic scope: full_files. Usage reference scope: 2 files. Architecture all: 2 files; 6 findings. ``` Each finding reads `path:line:column: rule: message`. A `warning:` prefix before the rule marks a warning, which never changes the exit code. Python `typing.Any` triggers both `type.annotation` and `type.broad`, so each position appears twice. The final line summarizes the run mode, audited file count and total findings. Because error-level findings are present, this run exits `1`—the normal initial baseline on an existing codebase; see [First full audit of an existing repository](#first-full-audit-of-an-existing-repository). If your sources live outside `src/` and `tests/`, update `include`: `--all` exits `2` when `include` matches no supported source files. After reviewing the initial audit, commit `.pluvy/pluvy.json` and gate new changes against a base commit such as `pluvy --base origin/main`. The sections below cover each step in detail. ## Installation ### Prerequisites - Python 3.12 or later. - `uv` is recommended for managing an isolated tool environment; see the [uv installation guide](https://docs.astral.sh/uv/getting-started/installation/). ### Installation from PyPI Install the CLI from [PyPI](https://pypi.org/project/pluvy/): ```sh uv tool install pluvy ``` Without `uv`, install with `pip`: ```sh python -m pip install pluvy ``` To run once without installing, use `uvx pluvy --all`. `uv tool install` places `pluvy` in uv's executable directory (`uv tool dir --bin`, typically `~/.local/bin`); run `uv tool update-shell` if that directory is not yet on your `PATH`. `pip` installs `pluvy` into the target Python environment's scripts directory. Pass `--force` to `uv tool install` when replacing an existing uv tool installation of the same name. ### Obtaining the source The PyPI package ships the CLI only. Sample policies under `examples/` and the agent skill under `.agents/skills/pluvy/` live in the [GitHub repository](https://github.com/sectrend-cn/pluvy); clone it when you need them. Below, `/path/to/pluvy` refers to that local checkout. Replace `pluvy` with `/path/to/pluvy` in either install command to install unreleased changes from source. ### Verification ```sh pluvy --help pluvy --root /path/to/project --all ``` `pluvy --help` confirms the installation and lists the supported flags: `--root` (default `.`), `--config` (default `.pluvy/pluvy.json`), `--format` (`text` or `json`), and one required mode from `--all`, `--staged` or `--base`. The second command audits `/path/to/project`. If that repository does not have a policy file yet, the command exits `2` and reports the missing file—create the policy as shown in [Configuration](#configuration) and run the check again. ### Obtaining the skill Copy `.agents/skills/pluvy/` from a repository checkout into the target project's skills directory. See [Agent integration](#agent-integration) for supported layouts. ## Configuration ### Establishing a repository policy Every target repository commits its own `.pluvy/pluvy.json` (resolved relative to `--root` in all modes). Pluvy has no subcommand that generates or initializes a policy; write and commit the file directly. The CLI defines only `--all`, `--staged`, `--base`, `--root`, `--config` and `--format`, plus `-h, --help`. You can start either by copying the [sample policy](https://github.com/sectrend-cn/pluvy/blob/main/examples/.pluvy/pluvy.json) to `.pluvy/pluvy.json` and adapting its paths, or by writing a minimal policy where an empty (or omitted) `checkers` object leaves all 22 checkers enabled with their defaults: ```json {"version": 2, "include": ["src/*", "tests/*"], "exclude": [], "checkers": {}} ``` Common settings to layer in as needed: - `include` / `exclude`: select which files participate in all checks (case-sensitive, `*` spans `/`, paths relative to the repository root). - `owners` under `architecture.owner`: assign a single accountable owner to every selected file. - `boundaries` under `architecture.import`: forbid specific cross-layer dependency directions. - `function_size`: set maxima for function lines, statements, complexity, nesting and parameters. When building up from a minimal policy, apply one step at a time and inspect the output before moving on: 1. Set `include` and `exclude` to match the repository's source and test directories. 2. Run `pluvy --all` to establish a baseline. Existing repositories usually exit `1` (see [First full audit of an existing repository](#first-full-audit-of-an-existing-repository)); if no supported source files match, `--all` exits `2` so you can fix `include` first. 3. Declare `owners` under `architecture.owner` for all selected files. 4. Add `boundaries` under `architecture.import`. 5. Tune `function_size` limits or declare project serializers under `type.broad.encoding` where justified. Threshold, exclusion, owner and boundary edits are policy changes: review each one with a full `--all` audit as described next rather than using it to silence findings. ### Discipline for changing the policy Changing thresholds, exclusions, owners, boundaries or checker `enabled` flags is an architecture decision, not a way to clear findings. Both the initial policy and every later revision require a full `--all` audit and human review before commit. While `.pluvy/pluvy.json` has staged changes in the Git index, `--staged` exits `2` rather than checking staged code against an unreviewed policy. Once committed, the revised policy takes effect immediately. If a pre-commit hook runs `pluvy --staged`, commit the reviewed policy change in its own commit and bypass the hook for that commit only (for example with `git commit --no-verify`). See [Checker configuration](https://sectrend-cn.github.io/pluvy/docs/checker-configuration.md) for all options, per-language coverage and analysis limits. ## Running Pass exactly one of the three mutually exclusive modes (`--all`, `--staged` or `--base `): - `--all`: audits every working-tree file matched by the policy, **including** Git-ignored files, exposing all existing debt. - `--base `: compares `` against the working tree, **including** untracked files (new files are audited in full). - `--staged`: reads only staged index blobs and the staged policy, ignoring unstaged working-tree edits. Canonical commands: ```sh pluvy --all pluvy --staged pluvy --base pluvy --root /path/to/project --all pluvy --all --format json ``` `--root` defaults to the current directory (and must be the repository root in Git modes); `--config` defaults to `.pluvy/pluvy.json`. They combine as `pluvy --root /path/to/project --config .pluvy/pluvy.json --all`. Exit codes: | Exit code | Meaning | |---|---| | `0` | No error-level findings; warnings do not change the exit code | | `1` | At least one error-level finding | | `2` | Configuration, encoding, filesystem or Git failure (including `--staged` while a policy change is staged) | Change modes (`--base` and `--staged`) parse full file snapshots for cross-reference resolution, then filter reported findings to **affected definitions and module statements**: editing inside a function selects the entire function (including decorators and signature), editing a class header selects the class, editing a module statement selects that statement, pure deletions keep a nearby line anchor, and untracked files are audited in full. File ownership and placement rules still apply to every changed file. Reports distinguish `full_files` from `affected_definitions_and_statements` via `scope`. Additional runtime rules: - An empty `--all` run fails as a configuration error (exit `2`), whereas an empty change run reports `0` files and exits `0`. - Syntax errors emit a warning on `stderr` without changing the exit code; enabled rules continue on the recovered tree, so results on broken syntax may be incomplete. - `--format json` outputs `mode`, `scope`, `files`, `usage_files`, `disabled_checkers` and `findings` (each with `severity`). Treat the JSON fields as implementation-defined across minor upgrades rather than a frozen external schema. ### Troubleshooting | Output | Cause | What to do | |---|---|---| | `Architecture gate error: [Errno 2] No such file or directory: '.../.pluvy/pluvy.json'` | No policy under `--root`, or the command ran from a subdirectory | Add the policy, run from the repository root, or pass `--root` | | `Architecture gate error: fatal: Needed a single revision` | The `--base` commit does not exist (for example `--base HEAD` before the first commit) | Create an initial commit first, or run `--all` | | `Architecture gate error: Policy changed in index; review it and run --all before adoption` | `--staged` ran with a staged policy edit | Commit the reviewed policy separately per [Discipline for changing the policy](#discipline-for-changing-the-policy) | | `Architecture base: 0 files; 0 findings.` with exit `0` | No diff against the chosen base (for example `--base HEAD` after committing task changes) | Not a valid pass: rerun against the parent of the task's first commit | ## Triage ### The three disposition paths 1. **Fix the code first**: a finding indicates a broken contract or boundary, so repairing the code is the default response. 2. **Approved next-line suppression (all supported languages)**: Python (`#`) and Go, Java, Rust and the JavaScript/TypeScript family (`//`) accept a standalone next-line directive naming one exact diagnostic ID and a reason. Use this only when **explicit human approval was granted beforehand**: the reason records that approval rather than proving safety, and reviewers must revisit it if the code's role changes. Block comments, wildcards, rule lists and missing reasons fail with `type.suppression`. Full syntax and rules: [Approved next-line diagnostic exceptions](https://sectrend-cn.github.io/pluvy/docs/comment-suppressions.md). 3. **Policy revision**: changing thresholds, exclusions or owners requires a standalone `--all` audit and architecture review; never weaken the policy to manufacture a passing run. ### Debt semantics `--all` surfaces repository-wide debt, while `--base` scopes findings to definitions and statements touched by a change; one mode cannot substitute for the other: - `0`: no error-level findings in this run's scope; warnings may be present. - `1`: at least one error-level finding in this run's scope; address each finding before completing the task. - `2`: the gate could not complete (configuration, encoding, filesystem or Git failure); fix the configuration or environment error first, then rerun the gate. ### First full audit of an existing repository On an existing codebase, the first `pluvy --all` run after creating a policy normally exits `1`. Treat that output as your baseline inventory rather than a tool error: 1. Inspect the findings and fix genuine contract or test defects first. 2. Where findings reflect accepted legacy debt or default limits that do not fit the codebase, adjust thresholds, exclusions or owners deliberately, then rerun `--all` and review. 3. Record which findings were fixed, which were accepted via policy configuration, and the review decision. ## Per-task gating Run Pluvy once at the end of every code task—before reporting the work complete—and report the mode, exit code, error/warning counts and key findings truthfully; the same standard applies to human and agent changes. The command-selection table (uncommitted edits, task commits, unknown start commit, and `--staged` scope), binding gate rules, post-run checks and report format are defined in the [pluvy skill](https://github.com/sectrend-cn/pluvy/blob/main/.agents/skills/pluvy/SKILL.md). Always check the file count on the summary line (`Architecture base: N files; M findings.`): `0 files` when code actually changed means the `--base` commit was chosen too late and does not count as a pass. ## Agent integration The skill bundle lives under `.agents/skills/pluvy/` in a repository checkout (`SKILL.md` plus `references/`). Three integration options are supported: 1. **Standard skills directory**: copy `.agents/skills/pluvy/` into the target project's or user's skills directory so compatible agents discover and load it automatically. 2. **Agent-specific directory adaptation**: when an agent reads instructions only from its own directory, choose copy versus symlink based on where that directory lives: - **Inside the repository (`--root`)**: apart from built-in infrastructure directories such as `node_modules` or `.venv`, which are always skipped, a directory symlink is tolerated during directory enumeration only if the policy proves no selected file can exist below its path or an ancestor. Either no `include` pattern reaches below it or an `exclude` pattern covers every descendant (`include: ["src/*", "tests/*"]` or `exclude: [".claude/*"]`). Pluvy never resolves the symlink target when deciding scope. Otherwise, including under the default `include: ["**"]`, copy the directory and re-copy it when its source updates. Out-of-scope directory symlinks never affect `--all` or `--base` enumeration and emit no warning. An in-scope directory symlink fails with exit code `2` (`Refusing to traverse symlink directory`) and is never skipped or downgraded to a warning. Pruning does not cover direct reads, so `--base` still refuses a symlink that Git lists as a selected changed or untracked source. Neither `--all` nor `--base` usage traversal consults `.gitignore` ([Running](#running)), so a Git-ignored in-scope directory symlink still fails with exit code `2`; `--staged` never walks the disk. `--base` walks the disk for usage evidence only when at least one selected changed or untracked current source is present (deletions alone do not count) and an `unused.*` checker is enabled; a `0 files` run skips that walk, and an exit-`0` `0 files` report does not validate expected changes ([Per-task gating](#per-task-gating)). See the agent integration notes for exact pruning rules. - **Outside `--root`** (such as a user-level skills directory): a symlink works cleanly and keeps a single source of truth. 3. **AGENTS.md pointer snippet**: for agents that read `AGENTS.md`, paste the snippet below into that file manually (never auto-rewrite a user's `AGENTS.md`): ```markdown When adopting, configuring, or running pluvy, or triaging its findings, first read `.agents/skills/pluvy/SKILL.md` and follow it. ``` For the general integration paths and limits, see [agent integration notes](https://github.com/sectrend-cn/pluvy/blob/main/.agents/skills/pluvy/references/agent-integration.md). Agents reading the published documentation over HTTP can fetch `/llms.txt` for a structured index, `/llms-full.txt` for the single-file plain-text corpus, or append `.md` to any documentation URL (for example `/docs/getting-started.md`). --- Source: https://sectrend-cn.github.io/pluvy/docs/checker-configuration.md # Checker configuration `.pluvy/pluvy.json` is the policy used when checking a target repository. It does not modify application behavior or rewrite source. Error findings return exit code 1; warning-only results return 0; invalid configuration and analysis failures return exit code 2. Each repository commits its own policy at this default path. Start with [the example](https://github.com/sectrend-cn/pluvy/blob/main/examples/.pluvy/pluvy.json) and adapt it to the repository's architecture. All selection and checker paths are relative to the repository root, not `.pluvy/`. Per-checker configuration examples are also bundled in the agent skill under [the checker index](https://github.com/sectrend-cn/pluvy/blob/main/.agents/skills/pluvy/references/checkers.md). `--config` selects the policy path; it stays relative to `--root` in every mode and must name a path inside the root. There is no automatic fallback to a root-level policy file. Staged checks read that exact path from the index and reject staged policy changes pending a full audit and review. Checker settings belong under `checkers`; top-level checker settings are rejected. The policy separates global file selection from checker options: ```json { "version": 2, "include": ["src/*", "tests/*"], "exclude": [], "checkers": { "function_size": {"lines": 50}, "architecture.object_model": { "enabled": false, "paths": ["src/plugins/*"] } } } ``` This example checks supported source files under `src/` and `tests/`, enforces a 50-line function limit, and disables non-underscore module-function checking. Other checkers retain their defaults, including language/rule dispatch checking. ## Options by checker Every checker supports a strict boolean `enabled`, defaulting to `true`. Omission of a checker or an option preserves its default. Flags such as `"false"` or `0` are errors. Unknown checker IDs and options are errors, including when a checker is disabled. Each entry configures one logical checker. Some checker keys group related diagnostics: `function_size` owns the five `size.*` IDs, `test.integrity` owns `test.tautology` and `test.vacuous`, `flow.handling` owns `flow.swallow` and `flow.fallback`, and `type.contract` owns `type.nullable` and `type.union`. The run-level `test.deletion` owns its single diagnostic outside analyzer registration. Every other checker name matches its diagnostic ID. There is no need to write `enabled: true` or entries that contain only default options. | Checker ID | Additional options and defaults | What it checks | | --- | --- | --- | | `structure.guarded_projection` | `min_fields: 3` (integer, at least 2) | Repeated guarded field copies in every supported language | | `function_size` | `lines: 50`, `statements: 50`, `complexity: 10`, `nesting: 3`, `parameters: 5` | All five function metrics | | `test.integrity` | `paths`: 20 default test-file globs | Tautological assertions and tests without a meaningful assertion | | `test.deletion` | `paths`: 20 default test-file globs, `snapshot_paths: ["*.snap", "__snapshots__/*", "*/__snapshots__/*"]`, `removed_assertions: 3` (integer, at least 0) | Removed test files, assertion erosion and changed snapshot paths in changed audits | | `flow.handling` | `max_chain: 3` (positive integer) | Swallowed exception handlers and long `??` chains whose defaults are all bare literals | | `type.contract` | `max_members: 4`, `optional_fields: 3`, `null_defaults: 3` (positive integers) | Aggregated nullable declarations, bare nullish fallbacks and oversized unions in TypeScript and TSX | | `type.annotation` | None | Broad or bare Python annotations | | `type.signature` | None | Missing Python parameter/return annotations | | `type.broad` | `encoding: {encoders: [], decoders: [], outputs: [], instance_outputs: []}` | Recognized broad type markers and JSON encoding outside proven output or permitted third-party inputs | | `type.boundary` | None | Unconverted recognized third-party results and callback inputs | | `unused.parameter` | None | Parameters without read usage | | `unused.function` | None | Non-exported functions and methods without references | | `unused.field` | None | Fields without reads, including write-only fields | | `unused.return` | None | Non-failing warnings for discarded known return values | | `type.assertion` | None | Unchecked type assertions and casts | | `type.suppression` | None | Shared foreign suppression directives in every supported language, `NOSONAR`/`CHECKSTYLE:OFF`/`noinspection` only in Java, `#[allow]`/`#[expect]` (and `cfg_attr` applying them) only in Rust, plus malformed or unused [next-line exceptions](https://sectrend-cn.github.io/pluvy/docs/comment-suppressions.md) | | `imports.wildcard` | None | Python wildcard imports | | `architecture.owner` | `owners: []` | Exactly one responsibility owner when owners are configured | | `architecture.structure` | `placements: []` | Selected source paths must match their configured owning locations | | `architecture.import` | `boundaries: []` | Forbidden source-to-import dependencies | | `architecture.dispatch` | None | Recognized language/rule identity dispatch | | `architecture.object_model` | `paths: []` | Non-underscore module-level functions in matching extension files | Metric maxima must be positive integers and are inclusive. Owners contain `name` and `paths`. Boundaries contain `name`, `sources`, and `forbidden_imports`. Ownership does not infer dependency permissions. All matching boundaries apply. An empty owner list, boundary list, or object-model path list provides no project-specific facts for that check to enforce. The three `type.contract` maxima are also positive integers and inclusive: a count equal to its limit passes, and only a greater count is reported. `optional_fields` applies per object type or interface declaration, `null_defaults` per innermost function body, and `max_members` per union expression after `null` and `undefined` members are removed. `flow.handling.max_chain` is also a positive integer and uses the same strict `>`: a `??` chain with as many operators as the limit passes, and only a longer chain is reported. A chain is reported only when every direct default is a bare non-nullish literal; parenthesized, asserted and called defaults are not literals, and a mixed chain stays silent. `test.deletion.removed_assertions` is a non-negative integer using the same strict `>`: an assertion count fall equal to the limit passes, and only a larger fall is reported. Whole-file deletion is not subject to this threshold. `include` and `exclude` are global and cannot be placed inside a checker. They use case-sensitive shell matching of root-relative paths, with `*` spanning `/`. Architecture-specific paths select where that one architecture check applies; they do not remove files from other checkers. `test.integrity.paths` selects which files the test-integrity checker analyzes. `test.deletion.paths` shares the same default and dialect for changed test files. The default is `["test_*.py", "*/test_*.py", "*_test.py", "tests/*", "*/tests/*", "*.test.js", "*.test.jsx", "*.test.ts", "*.test.tsx", "*.test.mjs", "*.test.cjs", "*.test.mts", "*.test.cts", "*.spec.js", "*.spec.jsx", "*.spec.ts", "*.spec.tsx", "*_test.go", "*Test.java", "*Tests.java"]`. The same `fnmatchcase` semantics apply: matching is case-sensitive, `*` spans `/`, and `**` or brace alternation have no special meaning. An empty list selects no files. The schema covers 22 logical checkers, which produce 29 built-in diagnostic IDs. Language syntax, region boundaries and a configuration example are documented in [the guarded projection checker reference](https://github.com/sectrend-cn/pluvy/blob/main/.agents/skills/pluvy/references/checkers/structure.guarded_projection.md). Custom plugin settings continue to belong to their typed plugin constructors; arbitrary custom checker names in this JSON are rejected. ## Language coverage Seven built-in analyzers cover six languages (including JSX and TSX syntax): Python (`.py`, `.pyi`), Go (`.go`), Java (`.java`), JavaScript and JSX (`.js`, `.jsx`, `.mjs`, `.cjs`), TypeScript (`.ts`, `.mts`, `.cts`), TSX (`.tsx`) and Rust (`.rs`). Every checker is enabled by default for each selected file. `enabled: false` disables that checker for every selected file: there is no `enabled` option scoped to one language or one file, and `include` / `exclude` drop files from all checkers at once, except that changed snapshot paths reported by the run-level `test.deletion` gate follow the changed set instead (see [Run-level deletion gate](#run-level-deletion-gate)). Architecture `placements`, `boundaries` and `paths` select where that one architecture check applies rather than enabling or disabling it. `owners` is not a scope selector: when it is configured and the checker is enabled, every selected file must match exactly one owner. Both are described in [Options by checker](#options-by-checker). Coverage differences therefore come only from the diagnostics an analyzer registers. Java analysis uses the locked `tree-sitter-java` grammar and needs no JDK or build step; Rust analysis uses the locked `tree-sitter-rust` grammar and needs no cargo or rustc. Every analyzer registers the same base set of 19 diagnostic IDs: - Usage: `unused.parameter`, `unused.function`, `unused.field` and `unused.return`, which is always a warning and never fails the gate. - Boundaries and directives: `type.boundary` and `type.suppression`. - Function metrics: `size.lines`, `size.statements`, `size.complexity`, `size.nesting` and `size.parameters`, all configured through the single `function_size` checker. - Architecture: `architecture.owner`, `architecture.structure`, `architecture.import`, `architecture.dispatch` and `architecture.object_model`. - Structure: `structure.guarded_projection`. - Testing: `test.tautology` and `test.vacuous`, both configured through the single `test.integrity` checker. `test.deletion` is not part of that per-language set: no analyzer registers it, and it is produced by the run-level deletion gate in `--base` and `--staged` mode. The remaining nine diagnostic IDs are registered per language: | Analyzer | Additional diagnostic IDs | | --- | --- | | Python | `type.annotation`, `type.signature`, `type.assertion`, `type.broad`, `imports.wildcard`, `flow.swallow` | | Go | `type.broad` | | Java | `type.assertion`, `type.broad`, `flow.swallow` | | JavaScript and JSX | `type.broad`, `flow.swallow`, `flow.fallback` | | TypeScript and TSX | `type.assertion`, `type.broad`, `type.nullable`, `type.union`, `flow.swallow`, `flow.fallback` | | Rust | `type.assertion`, `type.broad` | A registered diagnostic can only report for the analyzer that registered it: `type.annotation`, `type.signature` and `imports.wildcard` appear in Python files only, and `type.assertion` covers Python, Java, TypeScript, TSX and Rust but not Go or JavaScript. Rust has no exception handlers, so it registers neither `flow.swallow` nor `flow.fallback`. `type.broad` recognizes different markers in each language, in addition to the JSON encoding forms described in [Serialization boundaries](https://sectrend-cn.github.io/pluvy/docs/serialization-boundaries.md): | Language | `type.broad` markers | | --- | --- | | Python | `typing.Any`, `typing_extensions.Any` and `pydantic.JsonValue` references, plus internal `json.dumps`, `dump_json` and `model_dump_json` results | | Go | `any` and empty interfaces, plus imported `encoding/json` `Marshal`/`MarshalIndent` results | | Java | `java.lang.Object`, unbounded wildcards and recognized raw collections, plus recognized Gson/Jackson results | | JavaScript and JSX | `JSON.stringify` results only; JavaScript has no type annotations to check | | TypeScript and TSX | `any`, `unknown`, `object` and empty object types, plus `JSON.stringify` results | | Rust | `dyn Any` (including `std::any::Any`/`core::any::Any`/`alloc::any::Any`) and `serde_json::Value` paths (including variant paths), plus recognized `serde_json` `to_string`/`to_string_pretty`/`to_vec`/`to_value` results | Python broad annotation markers such as `Any` or `object` are reported by `type.annotation`, and a `typing.Any` reference additionally triggers `type.broad`, so one annotation can produce a finding from each checker. Coverage of a diagnostic does not promise complete evidence for every construct: resolution limits are described in [Third-party boundaries and usage](https://sectrend-cn.github.io/pluvy/docs/serialization-boundaries.md#third-party-boundaries-and-usage) and [Configuring encoding APIs](https://sectrend-cn.github.io/pluvy/docs/serialization-boundaries.md#configuring-encoding-apis). ## Run-level deletion gate `test.deletion` is a run-level gate, not an analyzer registration. It activates only for `--base` and `--staged`; `--all` does not run it. A deleted test file reports one error with its baseline declaration and assertion counts. A surviving changed test file is compared with its baseline: a missing declaration name in the multiset or an assertion count fall greater than `removed_assertions` reports one error per file. A changed path matching `snapshot_paths` reports one warning per path. Snapshot warnings are path signals over the changed set; global `include`/`exclude` do not filter them, so tighten `snapshot_paths` or disable the checker instead. Exact 100% renames are excluded from both the deletion and changed-path sets, so a partial rename still appears as a deletion. Next-line suppression is unavailable. A deleted file has no current snapshot, and an erosion finding has no corresponding current defect node, so `pluvy: ignore-next-line test.deletion` in a surviving file is an invalid directive and produces `type.suppression`. Disable the checker with `enabled: false` or tighten its globs when a reduction is intentional. Deleted files are not analyzed inputs: `files` in a text or JSON report counts only the current selected sources, while deletion findings are added from baseline evidence. Every `test.deletion` finding is anchored at line 1, column 1 with `scope: "file"`. An unmerged `--staged` index and a baseline blob that is not valid UTF-8 fail closed with exit code 2. ## Disabling and shared execution Set `enabled: false` to disable one checker across selected files. Text reports list disabled checker names, and JSON reports include a `disabled_checkers` array. For example, `"function_size": {"enabled": false}` disables all five function metrics and is reported as `function_size`. Findings still use `size.lines`, `size.statements`, `size.complexity`, `size.nesting`, and `size.parameters`. The same source may still violate a different enabled checker. For example, Python `typing.Any` can trigger both `type.annotation` and `type.broad`. Fully disabled rule bundles are skipped. A bundle with enabled diagnostics may still share traversal work across its checks; disabled diagnostics are filtered individually. Errors and undeclared output from an executing bundle still fail analysis. Disabling a checker does not permit broken plugin registration. Parsing constructs the context used by enabled checks. Invalid syntax emits warnings on stderr, including when `--format json` is selected, and checks continue on the recovered tree. Parser warnings are recorded apart from findings and never change defect counts or the exit status; they disclose that results may be inaccurate. Every language uses a tree-sitter context. Rules consume the available recovered syntax, while analyses requiring complete evidence may be unavailable. For Java, recovered syntax produces warnings and still permits syntax checks, while usage and boundary diagnostics require a complete parse. Parser infrastructure and semantic preparation failures return exit 2. When every diagnostic provided by an analyzer is disabled, parsing and bundle execution are skipped. `syntax.invalid` has been removed from the checker schema and rule declarations. Remove any `checkers["syntax.invalid"]` entry from existing policies; it is now rejected as an unknown checker. Parser warnings have no enable/disable option. Changing enable flags is a policy change subject to the same full-audit and review requirements as changing thresholds or boundaries. Staged-policy changes remain blocked by the staged gate; unstaged options do not alter index-based checks. ## Source structure `architecture.structure` enforces declared source-placement conventions. A file matching a placement's `paths` must also match at least one of its `allowed_paths`. Each matching placement is enforced independently; an unrelated placement does not affect the file. Patterns use the existing case-sensitive shell matching, where `*` can span directory separators. Paths are repository relative and pass through the same global include/exclude selection as other checks. The checker defaults to enabled with an empty `placements` list. For example, this repository requires language rule modules — `*_rules.py` modules and each language's `rules.py` — to live with the language plugins: ```json "architecture.structure": { "placements": [{ "name": "language rule modules belong with language plugins", "paths": ["src/pluvy/*_rules.py", "src/pluvy/languages/*/rules.py"], "allowed_paths": ["src/pluvy/languages/*"] }] } ``` `src/pluvy/python_rules.py` fails this constraint even if another policy assigns it a valid owner. `src/pluvy/languages/python/rules.py` passes: the `src/pluvy/languages/*/rules.py` pattern covers that path. Application composition in `plugins/builtins.py` imports `PythonTypeRule` from this module: the language owner covers that path, and existing dependency restrictions and object-model checks apply to it. Placement, ownership and import restrictions have independent enable flags. Placement diagnostics report the source path at line 1, name the constraint and list the allowed locations. All built-in languages use the same structural check. Changed modes apply it only to selected source files; staged checks use index paths and index policy, including when the working tree has moved a file. The gate never moves files itself. This is explicit convention enforcement. It does not infer a file's domain from its name, detect every misplaced class, or prove that a shared abstraction has real consumers. Those remain source-structure review obligations. The configured `*_rules.py` convention covers this project's language rule modules; other projects should declare their own domain-specific placements. Third-party boundary declarations (`third_party_modules`), cross-file usage resolution, built-in serializer rules and `checkers["type.broad"].encoding` options (`encoders`, `decoders`, `outputs` and `instance_outputs`) are documented in [Boundaries, usage and serialization](https://sectrend-cn.github.io/pluvy/docs/serialization-boundaries.md). --- Source: https://sectrend-cn.github.io/pluvy/docs/serialization-boundaries.md # Boundaries, usage and serialization This page covers `third_party_modules` boundary rules, cross-file usage and discarded-return resolution, and `type.broad` JSON serialization and output boundaries. For general policy structure and per-checker switches, see [Checker configuration](https://sectrend-cn.github.io/pluvy/docs/checker-configuration.md). ## Third-party boundaries and usage Declare third-party import specifiers explicitly at policy level: ```json { "third_party_modules": ["vendor.client", "@vendor/sdk", "example.com/vendor/sdk"], "checkers": {} } ``` The default is an empty list. Entries match the actual import module exactly (adapters may extend a configured crate root to sub-items imported from that external crate in Rust, while keyword roots stay internal); import aliases retain that identity. Do not list application modules to bypass typing. This setting grants a directional boundary exception, not a file or checker exemption. Internal dictionaries and other broad carriers remain checked. Disabling `type.boundary` disables its diagnostics but does not alter third-party classification used by the other type and field checks. A dictionary, or a directly forwarded dictionary parameter, can erase value types when every read supplies an argument to a configured library. Python `**kwargs`, Go maps and TypeScript `Record` annotations are recognized. Type assertions and suppression directives remain errors. JavaScript receives the same usage and boundary analysis; it still needs a separate type-aware checker. For a callback registered as a library argument, its return dictionary is library input. Its incoming dictionary parameters must be converted at callback ingress. The check recognizes declared constructors, concrete-return conversion functions and Python scalar conversions, including extraction of dictionary entries. A callback also called by application code does not gain a broad return contract. Library results cannot be returned or passed through application code raw. Values already constructed with a concrete generic library contract, and explicit `new` expressions, retain that contract. Type-only schema metadata and fields materialized by a configured external metaclass are not raw application result carriers. Mechanical recognition of a conversion does not prove its validator is honest. In Python, decorator factories supply declaration behavior rather than application payloads, while ordinary third-party payload results still require ingress conversion. This does not add a general payload exemption for decorators' arguments. Objects passed to configured libraries, including callback return objects, have all their declared fields treated as consumed. Configured external base classes also consume their class objects through metaclass construction. This repository lists `pydantic` for its externally materialized model fields. Field reads resolve through concrete receivers, annotations, constructors, imports and known bases; a write, initialization or deletion alone is not a read. Usage analysis runs automatically for Python, Go, Java, JavaScript/JSX, TypeScript/TSX and Rust. It resolves lexical scopes, closures, literal imports and Go files in the same package. Public Python module APIs, exported Go/JS/TS functions, non-private, annotated or overloaded Java methods, `pub`/`pub(crate)`, attributed, trait-impl and root `fn main` Rust items, recognized runtime entry points and declaration-only signatures retain their external-use contracts. Methods linked by resolved inheritance share parameter-use evidence. A read in any implementation makes the corresponding parameter used throughout its override family, including base and sibling implementations. Positional arguments match by position, keyword-only arguments by name, and variadic slots separately. Extra arguments and parameters unread throughout the family remain findings; unrelated same-named methods and constructors do not gain this exemption. This also applies to imported bases and JS/TS `extends` clauses. Structural interface relationships without resolved inheritance still require review. Python `self`/`cls`, JS `this`, Go and Rust receivers, blank `_` bindings and Rust names prefixed with `_` are not unused-parameter candidates. TypeScript constructor parameters marked `public`, `protected`, `private` or `readonly` can declare instance properties, and `unused.parameter` accepts resolved reads of those properties as usage of the exact constructor parameter declaration. Initialization and writes alone remain insufficient, and ordinary parameters or unrelated declarations with the same name remain reportable. `--all` links all selected snapshots. Changed audits read unchanged reference files from the same view: working files for `--base`, index blobs for `--staged`. Only the originally selected files receive findings; JSON `files` retains that scope and `usage_files` discloses the reference scope. These reads do not modify source or the index. In-process callers can use `AnalyzerRegistry.analyze_sources` with the built-in registry to obtain the same cross-file resolution; `engine.check` checks one snapshot. Custom registries can register a `SemanticParser` explicitly. Every finding includes `severity`, defaulting to `error`. `unused.return` is always a `warning`, `test.vacuous` is a `warning` when a test's only assertions are snapshot matchers, and `test.deletion` reports a changed snapshot path as a `warning`; text labels them and JSON retains them in `findings`. A known non-void local or resolved imported function result discarded as a standalone call, Python/Go `_` assignment, Rust `let _ = call;`, or JS `void` expression produces a warning. Unknown external return types are not guessed. Warnings alone leave exit status 0. Result classification uses the call expression as well as the declaration. TypeScript/TSX direct generic results such as `run(work: () => R): R` substitute explicit type arguments or infer the result from resolved callbacks. Python supports the corresponding imported `Callable[..., R]` contract with a PEP 695 parameter or an imported `typing.TypeVar` declaration. JavaScript supports direct forwarding of an unchanged callback parameter. A callback's declared contract takes precedence over its body; an unannotated callback with no value returns supplies no-result evidence. Expression bodies can call resolved local or imported functions. Each invocation is classified independently. Promises, coroutines, generators and containers remain value results, even when their payload is `void` or `None`. Java `Void` and Go empty structs also remain values; these languages cannot substitute a no-result type for a generic value parameter. Their existing declaration and overload fallback remains unchanged. Inference distinguishes no-result, value-result and unresolved evidence. Unresolved cases retain the declaration-based warning behavior. It does not implement compiler overload selection, arbitrary type aliases, class-level generic substitution, generic callback contextual typing or general dataflow. Overloaded TypeScript callbacks, reassigned callbacks, destructured/rest parameters, unsupported wrappers and unresolved external callbacks do not prove `void`. Python keyword argument binding and generic relationships outside direct callback results retain the fallback. Nested generic calls inside a resolved callback expression are supported; forwarding through generic parameter environments is not. There is no compiler runtime dependency. Cross-file inference reads declarations and callbacks from the same selected snapshot view as usage resolution. No result is cached on a declaration or across analysis sessions; staged checks use index content even when worktree signatures or callback bodies differ. Exact-line suppression is applied after inference, so a suppression targeting a now-proven void call becomes stale. These are bounded semantic checks, not compiler or whole-program proofs. Dynamic imports, arbitrary aliases, reflection, dynamic attributes, complex generic flow, framework registration and external consumers may require review. An unresolved member read or protocol dispatch defers same-named member candidates instead of asserting they are unused. Exported APIs are not automatically declared dead. Import resolution uses the available policy-selected snapshots; package/build alias resolution is not a replacement for language tooling. Review remaining candidates before changing code. The gate never removes or rewrites unused code. Java evidence is syntax-backed rather than javac type checking. Overload selection, generic substitution, reflection, annotation processing, generated accessors, wildcard/static-member project linking, fully qualified expression resolution and external classpaths are not resolved at compiler level. Nested or anonymous class ownership, generated members and unresolved external references retain the shared engine's inference limits. Rust evidence is syntax-backed rather than rustc or cargo resolution. Trait dispatch through generic bounds, `Deref` chains beyond `Box`/`Rc`/`Arc`/`Cow` annotations, cross-file `use crate::...` or `super::...` module linking, macro-generated code and encoder calls written inside macro invocations are not resolved; `macro_rules!` definition bodies are skipped completely by read collection (so fields or methods referenced only inside a macro definition can still be reported), whereas `.name`/`::name` tokens inside macro invocation arguments count as unresolved reads within Rust files only. Trait `impl` blocks do not share parameter-read evidence across implementations, and `#[derive]` items (including single-level `#[cfg_attr(..., derive(...))]`), `PhantomData` fields and non-wildcard struct patterns count as field reads. In `third_party_modules`, configuring an external crate root (such as `vendor_api`) classifies direct crate-qualified paths anywhere in the file (`vendor_api::Client::fetch()`, `::vendor_api::Client::fetch()`), crate-root aliases and explicit sub-item imports from that crate (single, grouped, nested or aliased; multiple crate roots do not interfere). Relative local `mod` imports, keyword roots (`crate`, `self`, `super`, including whole-root aliases such as `use crate as api;`), sibling crates (`vendor_api_ext`) and wildcard imports (`use vendor_api::*;`) are not classified; Python, Go, Java and the JavaScript family retain exact import matching. Configuring a full item path (`vendor_api::Client`) classifies only explicitly `use`-imported names, not direct paths. Local `mod` shadowing applies per directly enclosing module while leading `::` paths always target external crates (known limit: a leading `::` crate-root binding shares statement-region visibility, so inside one block under a local `mod vendor_api`, a relative `vendor_api::...` path in the same sequential statement region as `::vendor_api::...` is conservatively classified as external, whereas an earlier sequential region such as a preceding `let` initializer or another function stays exact). Listing an encoder crate itself (such as `serde_json`) in `third_party_modules` reports both `type.boundary` and `type.broad` on a consumed unemitted encoding result (returned, read later, or passed through `.unwrap()` even if discarded), whereas directly discarding the raw call result (`let _ = serde_json::to_string(&1);`, statement-position call or unread local, including behind `?`) reports only `type.broad`. ## Serialization and output boundaries `type.broad` reports serializer calls that erase concrete internal application objects into JSON text or bytes unless every observed use reaches a proven output destination or a permitted outbound library call. Alias resolution and output forwarding share the same semantic engine across all six supported languages. Disabling `type.boundary` does not disable serialization checks or alter their boundary evidence; disabling `type.broad` disables its serialization findings. The `third_party_modules` policy above applies directionally: serialized data may be passed directly to a configured library (including keyword arguments, inline containers where the language forwards containers—Rust struct, tuple and array literals do not count—and returns from callbacks used exclusively by that library), or held in a single-assignment local whose resolved reads all reach permitted library inputs or proven outputs. Internal consumers, retained fields, ordinary helper returns, intermediate transformations, dictionary keys, reassigned carriers and encoder-to-decoder round trips remain findings—even when the serializer module itself is listed in `third_party_modules`. When a receiving library's module is listed in `third_party_modules`, passing a member-level encoder result directly to one of that library's class methods—such as `VendorModel.model_validate_json(item.model_dump_json())`—receives the same directional library-input exemption as `json.dumps`. Declaring that target method in `decoders` for its resolved identity rejects the round trip. ## Built-in serializers and outputs by language ### Python - **Recognized encoders and decoders**: `json.dumps` and `json.loads` via module imports, renamed imports, `from json import dumps`, and stable single-assignment callable or module aliases (`encode = json.dumps`, `codec = json`). Python also treats explicit member calls named `dump_json` or `model_dump_json` (such as Pydantic `TypeAdapter.dump_json` and `BaseModel.model_dump_json`) as encoders without requiring a `pydantic` import or resolved receiver type. Name-level identities follow stable aliases and parentheses, whereas member-level recognition (built-in Pydantic entry points and configured `*.member` entries) matches only the explicit member name at the call site—`dump = ADAPTER.dump_json; dump(item)` and `(item.model_dump_json)()` are not recognized. Strings containing source examples and unrelated methods named `dumps` are ignored. - **Recognized outputs**: unshadowed `print` / `builtins.print`, imported `sys.stdout.write` and `sys.stderr.write`, `write_text` on a recognized `pathlib.Path` construction or stable local alias, and `write` or `print(..., file=...)` targeting an enclosing writable text `open` / `builtins.open` / `io.open` context or standard stream. `StringIO`, shadowed names and arbitrary `write` or `send` methods do not establish egress. ```python import json import vendor vendor.send(body=json.dumps({"count": 1})) # permitted when vendor is in third_party_modules print(json.dumps({"count": 1})) # permitted terminal output ``` ### JavaScript, TypeScript and TSX - **Recognized encoders and decoders**: native `JSON.stringify` and `JSON.parse`, including stable callable and module aliases (`const encode = JSON.stringify`, `const codec = JSON`). - **Recognized outputs**: unshadowed `console.log`/`info`/`warn`/`error`/`debug`, standard `process.stdout.write` and `process.stderr.write`, and imported `fs` / `node:fs` (including `fs/promises` and `node:fs/promises`) file write and append payload arguments (serialized filenames do not count). Computed members, destructured aliases and shadowed globals do not establish egress. ```javascript const encode = JSON.stringify; console.log(encode({ count: 1 })); const body = encode({ count: 1 }); consume(body); // reported by type.broad ``` ### Go - **Recognized encoders and decoders**: imported `encoding/json.Marshal` and `encoding/json.MarshalIndent` (encoders) and `encoding/json.Unmarshal` (decoder), preserving import and stable callable aliases. In `data, err := json.Marshal(value)`, only `data` is tracked as the serialized carrier; checking `err` stays independent. Predeclared or reassigned carriers, aggregate tuple forwarding, byte/string conversions and streaming encoders remain outside this proof. - **Recognized outputs**: imported `fmt.Print` / `fmt.Println`, `os.Stdout.Write` / `os.Stderr.Write` (argument `0`), and `os.WriteFile` (payload argument `1`). Arbitrary `io.Writer` methods and memory buffers do not establish egress by name alone. ### Java - **Recognized encoders and decoders**: one-argument `Gson.toJson` and Jackson `ObjectMapper.writeValueAsString` / `writeValueAsBytes` on imported, explicitly typed locals, parameters, fields or direct constructors; `Gson.fromJson` and `ObjectMapper.readValue` / `readTree` reject round-trip reconstruction. Multi-argument streaming overloads, `var` inference and unqualified `toJson` methods without receiver proof are not classified automatically. A configured `*.toJson` encoder entry enables receiver-agnostic recognition for explicit-receiver calls (including streaming overloads such as `gson.toJson(item, writer)` that the built-in adapter excludes), while implicit-receiver calls remain unproved. - **Recognized outputs**: unshadowed `System.out` and `System.err` `print` / `println` (argument `0`). ### Rust - **Recognized encoders and decoders**: `serde_json::to_string`, `to_string_pretty`, `to_vec` and `to_value` (encoders) and `from_str`, `from_slice`, `from_value` and `from_reader` (decoders), spelled via explicit `use` bindings, aliases, leading `::` or crate-qualified paths (even alongside `use serde_json::value::*;`). A local `mod serde_json` shadows the external crate only in the directly enclosing module, whereas leading `::serde_json::...` always targets the external crate across expanded `use` items. Each returns a `Result`, so the carrier is tracked through `?`, zero-argument `.unwrap()` or single-argument `.expect(...)` (other arities such as `.unwrap(1)`, `.expect()` or `.expect(a, b)` are not transparent, including inside macro arguments). `.map_err(...)`, `to_writer` and `impl Serialize::serialize` are not transparent or classified. - **Recognized outputs**: `println!`, `print!`, `eprintln!` and `eprint!` arguments (including inline format captures `{name}`/`{name:?}`/`{name:spec}` and explicit positional or named arguments when the first argument is a literal format string—non-literal first arguments such as `concat!(...)` do not parse captures; captures resolve in the value namespace to the visible binding at the capture site, require single assignment with all reads reaching permitted outputs, let explicit named arguments in standard format macros override same-named inline placeholders with raw labels `r#name` compared as `name`, accept named arguments referenced by `{}`/`{N}` with `{}` and `.*` precision advancing the implicit position counter, and do not treat named width/precision parameters `{v:width$}`/`{v:.decimals$}` or `}`-fill modifiers as serialization captures); `std::io::stdout()`/`stderr()` (optionally `.lock()`, borrowed/parenthesized or held in a single-assignment local) `write_all`/`write` payload `0`; `std::io::Write::write_all`/`write` when argument `0` is a proven `stdout()`/`stderr()` receiver (optionally `.lock()`); `std::fs::write` payload `1`; and `std::fs::File::create(...)` (after unwrapping `Result` via `?`, zero-argument `.unwrap()` or single-argument `.expect(...)`, including single-assignment local handles) `write_all`/`write` payload `0`. Local `mod std` shadowing applies per enclosing module while `::std::io::stdout()` always targets the external standard library. Memory buffers (`&mut Vec::new()`), arbitrary `Write` calls without receiver proof, `OpenOptions::new()...open(...)`, `tokio::fs::*`, `write!`, `dbg!` and `format!` do not establish egress. - **Direct-flow limits**: an encoded value is exempt only when the value itself reaches a recognized output or permitted third-party input directly (or through a single-assignment `let`, `?`, `.await`, zero-argument `.unwrap()`, single-argument `.expect(...)`, borrows `&`/`&mut`, parentheses or `as` conversions). Struct, tuple and array literals (including `(p,)` and `[p]` inside macro arguments) do not prove container forwarding, and derived values (`text.len()`, `text.as_bytes()`, `.map_err(...)`, range expressions `text..`, slices and indexing `&text[..1]`/`text[0]`) do not exempt the carrier—use `serde_json::to_vec` with `stdout().write_all(&bytes)` rather than `to_string` with `write_all(text.as_bytes())`. - **Known limits**: declarations and references match by source spelling, so raw identifiers (`r#p`) do not match `p` (except format labels `r#name = ...`); a block-local `struct`/`enum`/`trait`/`union`/`mod` still shadows an outer encoded binding for format captures; inline format captures inside a closure are not attributed to an outer encoded binding; format/print macros are matched solely by final path segment without modeling local `macro_rules!` shadowing, macro path imports or local `mod std` shadowing of `std::println!`; and value alias chains exceeding the 64-step path-spelling budget yield no resolved path spelling. ```rust use std::fs::File; use std::io::{self, Write}; fn emit(event: &Event) -> io::Result<()> { let printed = serde_json::to_string(event)?; println!("{printed}"); // permitted terminal output let streamed = serde_json::to_vec(event)?; io::stdout().write_all(&streamed)?; // permitted standard-stream output let saved = serde_json::to_vec(event)?; File::create("event.json")?.write_all(&saved)?; // permitted file output let wrapped = serde_json::to_string(event)?; let _envelope = Envelope { body: wrapped }; // reported by type.broad let text = serde_json::to_string(event)?; io::stdout().write_all(text.as_bytes())?; // reported by type.broad Ok(()) } ``` Across all languages, conditional result branches (`cond ? encode(x) : text`) retain all-consumer flow, while using an encoded value as a condition or passing it across functions without configured contracts remains a finding. ## Configuring encoding APIs Extend `type.broad` in `.pluvy/pluvy.json` to recognize project-specific or third-party serializers and approved output APIs. These lists add to built-in recognition; empty or omitted lists keep all built-in checks active. ```json { "checkers": { "type.broad": { "encoding": { "encoders": ["orjson.dumps", "@vendor/codec.encode", "*.to_wire"], "decoders": ["orjson.loads", "@vendor/codec.decode"], "outputs": [ {"call": "transport.publish", "arguments": [1], "keywords": ["body"]} ] } } } } ``` The [example policy](https://github.com/sectrend-cn/pluvy/blob/main/examples/.pluvy/pluvy.json) contains a compact version of this configuration. Choose API names from the target project: - `encoders`: exact qualified functions returning serialized data, or the restricted receiver-agnostic member form `*.member` (a `*.` prefix followed by one ASCII identifier; a bare method name remains an exact qualified identity). Their results must still flow exclusively to permitted outputs; registration is not an exemption. - `decoders`: exact qualified reconstruction functions. Passing an encoding into these (directly, via aliases or through forwarded locals) reports `type.broad`. - `outputs`: exact `call` identities with payload selectors. `arguments` lists zero-based positional indexes; `keywords` lists Python keyword names. At least one selector is required; an empty list never matches all arguments. With the configuration above, `publish("topic", encoded)` and `publish(body=encoded)` pass, whereas `publish(encoded, "payload")` reports `encoded`. Positional offsets after `*args` or `...args` cannot prove a configured slot, though explicit Python keyword arguments after `*args` still can; `**kwargs` is not expanded into named slots. Exact API names match resolved import identities rather than local aliases: Python `from orjson import dumps as pack` matches `orjson.dumps`, and `import { encode as pack } from "@vendor/codec"` matches `@vendor/codec.encode`. A `*.member` entry matches explicit-receiver member calls by member name (bare calls, Java implicit-receiver calls, aliases and parenthesized callees do not match). Names are exact and case-sensitive; blank strings, whitespace, general wildcards (such as `orjson.*`), non-integer indexes and unknown fields fail configuration validation even when `type.broad` is disabled. This configuration applies uniformly across Python, Go, Java, Rust, JavaScript, JSX, TypeScript and TSX. Exact qualified API names do not resolve arbitrary instance methods, computed members or dynamic imports without import evidence; Rust macro outputs are matched by their path with zero-based top-level comma-separated `arguments` (ignoring commas inside nested or commented turbofish generics), skipping a leading string literal when it is a format string (always for built-in print macros, and for other configured macros only when that leading string contains `{`—so `vendor::publish!("{}", payload)` places `payload` at `0` while `vendor::publish!("tag", payload)` places `payload` at `1`), provided the configured slot receives the encoded value directly rather than a derived expression such as `payload.len()`, `&payload[..1]` or `payload[0]`. Decoder rejection always takes precedence over both `outputs` declarations and `third_party_modules` input exemptions, and encoding settings never exempt broad annotations (`Any`, `any`), casts or unconverted library return values. ### Source-owned instance output callbacks Approve a specific class-owned method or callback property (or a named struct receiver in Go) without exempting every same-named method in the codebase: ```json { "checkers": { "type.broad": { "encoding": { "instance_outputs": [ { "path": "src/analysis/command.ts", "class_name": "Cli", "member": "out", "arguments": [0] } ] } } } } ``` This permits `this.out(JSON.stringify(entry))` inside `Cli` in that exact file. `instance_outputs` is an explicit policy trust boundary: the analyzer does not trace dependency injection sites to verify every runtime implementation of `out`, so review the injection contract before adding an entry and revisit it when implementations change. Selector rules shared by all languages: - `path`: exact, case-sensitive, normalized repository-relative POSIX path (no leading `/`, backslashes, wildcards, `.` or `..`). - `class_name` and `member`: exact ASCII identifiers (including `$` and `_`), each resolving to a single unambiguous declaration in the snapshot; unmatched or duplicate declarations remain inert so shared policies work during partial audits. Parser-recovered snapshots fail closed. - `arguments`: non-empty list of zero-based non-negative integer payload positions. Per-language receiver rules: - **JavaScript, TypeScript and TSX**: recognizes direct `this.member(...)` calls inside instance methods, field initializers and nested arrow functions. Ordinary nested functions, explicit `this` parameters, object literals, static members, getters/setters, decorated or computed members, inherited-only members, receiver aliases and extracted callbacks are not approved. - **Python**: recognizes `self.out(...)` (using the method's actual first positional parameter name, including closures capturing it) on fields declared on the class or initialized in `__init__`. Decorated methods (`@staticmethod`, `@classmethod`, `@property`), variadic or reassigned receivers, inherited-only members and keyword argument calls (`self.out(line=encoded)`) are not approved. - **Go**: `class_name` names the struct receiver type and `member` names its direct method or function-valued field in that same file (for example, `c.out(data)` inside `func (c *Cli) run(...)`), supporting value/pointer receivers and closures capturing the unchanged receiver. Embedded fields and reassigned receivers remain checked. - **Java**: recognizes direct `this.out(encoded)` on a single non-overloaded instance method, or `this.out.accept(encoded)` when `out` is a field typed as explicitly imported `java.util.function.Consumer` (where `arguments` indexes into `accept`). Lambdas preserve the enclosing `this`; static contexts, anonymous classes, overloads and implicit `out(...)` calls without `this.` are not approved. - **Rust**: no instance outputs are recognized; method calls on `self` or any receiver never establish egress by member name alone. Use explicit `outputs` entries for approved APIs. --- Source: https://sectrend-cn.github.io/pluvy/docs/comment-suppressions.md # Approved next-line diagnostic exceptions Every supported language accepts a standalone line comment on the physical line immediately before a finding, using that language's line-comment marker (`#` for Python; `//` for Go, Java, Rust, JavaScript, JSX, TypeScript, and TSX): ```ts // pluvy: ignore-next-line type.broad -- Serialized test input. const input = JSON.stringify(payload); // pluvy: ignore-next-line type.broad -- Expected wire response. assert.equal(result.content, JSON.stringify(expected)); ``` ```python # pluvy: ignore-next-line type.annotation -- Legacy adapter boundary. value: object = read_payload() ``` ```go // pluvy: ignore-next-line type.broad -- Generated wire payload. type Payload any ``` ```java // pluvy: ignore-next-line type.broad -- Framework callback signature. void handle(Object value) { consume(value); } ``` ```rust // pluvy: ignore-next-line type.broad -- Erased audit payload. fn erase(value: Box) { consume(value); } ``` ## Approval requirements Use a next-line directive only after obtaining explicit human approval for that exception. The non-blank reason after `--` records that approval; it does not prove safety on its own. Revisit the exception whenever the surrounding code or its callers change. Foreign linter and type-checker suppression markers remain prohibited across all supported languages and report `type.suppression`: - **All languages**: `noqa`, `type: ignore`, `pyright: ignore`, `mypy: ignore`, `@ts-ignore` / `@ts-expect-error` / `@ts-nocheck`, `eslint-disable` variants, `nolint`, and `lint:ignore`. - **Java additionally**: `NOSONAR`, `CHECKSTYLE:OFF`, `noinspection`, `@SuppressWarnings`, and `@SuppressFBWarnings` (keep those markers out of the reason text in Java files as well, since Java's comment check matches them independently). - **Rust additionally**: every `#[allow(...)]` and `#[expect(...)]` attribute, including `#![allow(...)]` crate-root forms and `#[cfg_attr(..., allow(...))]` / `#[cfg_attr(..., expect(...))]` attributes, whatever lint they name; fix the code instead of silencing rustc or clippy. ## Selector and placement rules - **Exact diagnostic ID**: Name one registered diagnostic ID for the file's analyzer—for example `size.lines` rather than the `function_size` checker key. Unknown IDs, wildcards, comma-separated lists, `type.suppression`, and the run-level `test.deletion` diagnostic are rejected as `type.suppression`. - **Standalone physical line**: Place the directive on its own line immediately above the line where the finding starts. Trailing end-of-line comments, block comments (`/* ... */` in Go, Java, Rust, and the JavaScript family), file-wide directives, missing reasons, and blank or comment lines between the directive and its target report `type.suppression` and do not suppress any finding. - **Exact target coverage**: Every finding on that immediately following line matching the named diagnostic ID is omitted; all other rules and lines remain active. For example, suppressing `type.broad` on a mixed line covers both broad annotations (`any`, `unknown`) and serialization calls on that line—split mixed statements first if approval applies to only one part. - **No unused directives**: A syntactically valid directive whose target line emits no matching finding (including when its checker is disabled) reports `type.suppression`. ## Snapshot and changed-scope behavior Pluvy reads suppression comments from the exact immutable source snapshot under audit: `--staged` reads Git index blobs rather than unstaged working-tree edits. In `--base` and `--staged` runs, unused-directive checks run only when the target line falls within the audited change scope, so partial audits do not flag unrelated files. Maintainer and implementation details for the suppression parser live in the skill reference at [comment-suppressions.md](https://github.com/sectrend-cn/pluvy/blob/main/.agents/skills/pluvy/references/comment-suppressions.md). --- Source: https://sectrend-cn.github.io/pluvy/docs/engineering-standards.md # Shared engineering standards This document records the engineering policy used to build Pluvy itself and the design specification behind its checkers. Rules enforced mechanically by `pluvy` are listed in [Automated gate](#automated-gate) (with options in [Checker configuration](https://sectrend-cn.github.io/pluvy/docs/checker-configuration.md)); the remaining requirements apply during human and agent code review across production code, tests, fixtures, adapters, scripts and helpers. ## Ownership and architecture 1. Give every file a named domain, application, infrastructure or presentation responsibility. Keep stage-specific contracts, interpretation and validation inside their stage. Avoid catch-all `utils`, `common` and `helpers` ownership. 2. Shared scheduling and lifecycle infrastructure knows only its narrow protocol. It must not import concrete stage payloads, even through type-only imports. Compose concrete implementations at a registration/composition boundary. 3. One component owns each mutable state, transaction, resource lifetime and terminal failure. Preserve cancellation, cleanup, ordering and exactly-once completion through refactors. Keep domain rules independent of adapters. 4. Use composition, cohesive objects and narrow interfaces. An abstraction must own policy, an invariant, a real boundary or a resource lifetime. Small pure functions are welcome. Avoid delegation-only hierarchies and callback bags that obscure domain ownership. 5. Implement language adapters and rules as independently registered classes with narrow typed interfaces. Language objects own identity, suffixes, tree-sitter grammar and syntax interpretation. Application composition owns enabled and required rules and connects them to compatible language capabilities. All language parsers produce the same concrete tree-sitter context; shared rules consume typed capabilities without selecting language identities or importing language implementations. Keep exceptional grammar and language-specific checks with the language owner. Shared engines and discovery use registration; do not dispatch on language or rule identities with conditionals or callback bags. Rule objects own their behavior; forwarding wrappers around procedural dispatch do not establish ownership. Configure `checkers["architecture.object_model"].paths` for extension implementation paths. [Plugin architecture](https://sectrend-cn.github.io/pluvy/docs/plugin-architecture.md) records the decoupled language/rule design, the current runtime and its compatibility behavior. 6. Export only consumed supported APIs. Test public behavior through concrete seams. Do not expose internals or clone domain models merely to simplify tests. 7. Search existing types before introducing a DTO, payload or fixture wrapper. Keep one canonical type per contract. A second type needs distinct domain meaning, external schema or lifecycle invariants and a tested transition. 8. Organize source around the feature or domain that owns its behavior. Keep feature-specific rules, validation and supporting contracts with that owner; a technical label such as `rules`, `helpers` or `models` does not by itself justify moving them to the package root or a shared directory. Promote code to a shared owner only when it has a real shared responsibility and concrete consumers. For example, Python-only type rules belong under `languages/` alongside the Python plugin; shared analysis engines depend on their typed interfaces. Enforce declared placement conventions with `checkers["architecture.structure"].placements`. Review placement together with imports and canonical ownership; path checks cannot infer domain meaning. For language analysis, retain the original tree-sitter tree and source locations. Extract only the typed facts needed by consumers; reuse canonical contracts. Do not build a generic dictionary AST, a second universal AST or a capability bag requiring casts. Grammar adapters interpret syntax; shared analysis owns resolution and reusable evidence; rules apply policy. An analysis session owns each exact snapshot's parse lifetime and mutable resolution state. Adapters that cache per-snapshot evidence keep that state on the instance returned by `for_session()`. Required unsupported capabilities fail registration; optional unavailable analysis is explicitly reported. Rule identity ownership is unique within each composed execution. The repository import policy prohibits runtime Python AST dependencies and language-owned analyzer composition. It also keeps concrete grammar dependencies (`tree_sitter_python`, `tree_sitter_go`, `tree_sitter_java`, `tree_sitter_javascript`, `tree_sitter_typescript` and `tree_sitter_rust`) out of shared analysis, parsing and rule modules; language plugins own their grammars. The implementation follows the approved decoupled language/rule design, and its inference limits remain review obligations. Policy enforcement does not authorize suppressions. ## Types and boundaries Preserve known concrete types end to end. Do not widen to `Any`, `object`, `any`, `unknown`, `interface{}`, generic JSON trees, broad base classes, bare collections, unconstrained generics or unrelated unions and later reconstruct the original. Use discriminated domain alternatives and typed keys/elements. Narrow untrusted input once, at actual ingress, into a declared contract; encode at actual egress. Do not carry structured application payloads internally as JSON strings or bytes. Do not use casts, non-null/double assertions, type suppressions, unchecked model construction, permissive schemas, reflection bags, serialization round trips or broad mocks to bypass this rule. The third-party boundary exception below permits only the erasure needed by that boundary. Legitimate syntax trees retain a real syntax-domain contract. Literal test source snippets are source inputs, not serialized application payload carriers. JSON encoding uses shared alias and output-flow analysis with language-owned serializer/API recognition. Python JSON encoding is permitted at proven output destinations: unshadowed `print`, imported `sys.stdout`/`sys.stderr` writes, `pathlib.Path.write_text`, and text writes to a writable `open` context. Python also recognizes `TypeAdapter.dump_json` and `BaseModel.model_dump_json` by member name without import or receiver-type evidence; any same-named member call is treated as encoding and remains a finding unless its result reaches a permitted output. A single-assignment local may forward the encoding only when every observed use reaches permitted output. Memory buffers, arbitrary write-like method names, internal consumers and decoding the encoding back into application data do not establish egress. Other output APIs need actual configured library evidence, reviewed `type.broad.encoding.outputs` payload declarations, source/class/member-scoped `instance_outputs` approvals, or an explicit language adapter. Encoder/decoder declarations under `type.broad.encoding` extend recognition and retain round-trip rejection. JavaScript/TypeScript/TSX apply the same policy to native `JSON.stringify`, with recognized console, standard-stream and imported filesystem outputs. Go recognizes imported JSON Marshal/MarshalIndent results with explicit byte/error separation; Java recognizes selected imported Gson/Jackson serializer signatures; Rust recognizes `serde_json` `to_string`/`to_string_pretty`/`to_vec`/`to_value` results directly reaching recognized print macros (`println!`, `print!`, `eprintln!`, `eprint!`, matched by final path segment), receiver-proven standard stream or `std::fs::File::create` writers, or `std::fs::write`, while encoder calls written inside macro invocations stay unrecognized because macro bodies are untyped token trees. Scoped instance outputs use language-owned receiver proof in Python, Go, Java, JavaScript, TypeScript and TSX; Rust does not recognize instance outputs. See [encoding configuration](https://sectrend-cn.github.io/pluvy/docs/serialization-boundaries.md#configuring-encoding-apis) for exact signatures, output slots and conservative inference limits. At an actual call into third-party code, a type-erased dictionary is permitted as a library input, including keyword arguments. Keep the application's contract concrete until that outbound boundary. Convert values returned by the library into declared typed objects at ingress before carrying them through application code. A forwarding parameter may use the library dictionary contract when every use goes directly to that library. This exception does not permit erased internal storage, application return types or general transport between components. Callbacks reverse the direction: callback parameters are outputs of third-party code and must be narrowed into typed objects at callback ingress; the callback's return value is input to the library and may use the erased dictionary required by its contract. Establish the actual third-party call or callback registration; a parameter name such as `kwargs`, an import alone, or a boundary-like function name is not sufficient evidence. Casts and unchecked reconstruction do not count as conversion or validation. TypeScript `as const` and checked `satisfies` preserve useful contracts and are allowed. Go capability interfaces must declare the operations their consumers need. JavaScript public contracts need concrete JSDoc or a typed boundary with type-aware checking. Other exceptions require explicit case-specific user approval, an exact path/symbol, rationale, validation and removal conditions. The gate supports explicit per-checker `enabled` flags in project policy; these are reviewable policy decisions and do not authorize type erasure or create a blanket boundary exemption. Source suppression directives remain prohibited except for explicitly approved next-line diagnostic exceptions available in every supported language, described in [comment suppressions](https://sectrend-cn.github.io/pluvy/docs/comment-suppressions.md). Required facts must not default to guessed values, success, an arbitrary first entry or an empty payload. Model absence, rejection and unresolved evidence explicitly. Shape validation does not prove authorization, freshness or business acceptance; preserve those checks at their actual use points. ## Guarded field projections Review repeated conditional field copies as a contract and mapping responsibility in every supported language. Three distinct guarded destination fields in one consecutive local region trigger `structure.guarded_projection`, independently of function complexity. A candidate copies the tested source field or a primitive literal established by equality, with an absent/empty other branch. Conditional object/dictionary spreads have the same policy where the language supports them. Keep source receiver and destination construction identities distinct. Do not merge across unrelated statements, properties, calls, reassignments, nested functions or control-flow regions. Dynamic keys, transforms, business operations, validation and unproved predicates do not establish this pattern. Findings retain locations and predicate distinctions; no autofix is safe by default. Remediation must preserve concrete field associations, field types, omission semantics, evaluation order and exceptions. Where required nullable fields are the actual domain contract, a concrete object can express the mapping. Where omission is required, retain it through reviewed typed construction, or change the owning contract together with its consumers. Do not replace guards mechanically with spreads, casts, erased dictionaries, serialization filtering or forwarding helpers, and do not weaken optional-field types just to pass the gate. Turning assignments into conditional spreads does not remove the pattern, and repeated validation of already typed internal fields is not remediation. Exact adapter coverage and conservative inference limits are documented in [structure.guarded_projection.md](https://github.com/sectrend-cn/pluvy/blob/main/.agents/skills/pluvy/references/checkers/structure.guarded_projection.md). ## Unused declarations and results Report unused parameters, functions and class fields. A field must have a read usage: declaration, initialization and subsequent writes alone do not make it used. Associate reads with the actual declaring type and instance; a same-named field on another class is not evidence. Account for callers, closures, inherited contracts, registered callbacks and framework entry points before declaring a function unused. For methods in a resolved inheritance contract, count a parameter as used when its corresponding slot is read by any implementation in that override family. A parameter unread throughout the family, or an isolated callback parameter with no read evidence, remains reportable. Explain required signature constraints rather than deleting the parameter. When an object is passed into third-party code, all of that object's fields may be treated as used by the library. Apply this exemption to the actual object passed, including an object returned by a registered callback, and do not infer it for unrelated objects or for values arriving from the library. Warn when a non-void return value is discarded. Such warnings do not fail the gate. A call made solely for side effects can still discard a meaningful result; absence of return-type evidence is not proof that the call returns a value. Record the checked scope and unresolved external usage instead of claiming a repository-wide unused declaration from an isolated source snapshot. ## Readable implementation Use meaningful names, one operation and abstraction level per function, minimum visibility and the language's standard formatter. Prefer named domain operations. Callbacks belong to the component that owns their behavior. Do not compress code or split resource/transaction ownership merely to satisfy a metric. Default maxima: **50 substantive physical lines, 50 statements, complexity 10, control nesting 3, five parameters**. Count function signatures and nested bodies in line spans. Blank/comment lines and Python docstrings are excluded. Nested functions receive independent control-flow checks; their decisions do not inflate the enclosing function's complexity. Go grouped parameter names count separately; Go receivers, Python `self`/`cls` and Rust `self` receivers do not consume the argument budget. Document purpose, public contracts, invariants and failure behavior. Use Python docstrings, public API documentation and durable architecture records. This shared policy does not require or ban ordinary rationale comments. Follow the owning project's explicit comment policy. Checker-suppression comments are prohibited except for the explicitly approved next-line mechanism available in every supported language. Reasons record human approval; the checker does not prove the exception is safe. Do not delete existing rationale or code without authorization. Use operational logs that explain event, operation, outcome and next action with appropriate levels, stable identifiers, bounded values and one terminal-error owner. Normalize control characters and redact secrets. Use lazy Python logging. Approvals granted in other projects do not transfer here. ## Automated gate | Rule | Mechanical evidence | | --- | --- | | `size.lines` / `size.statements` | Function token-bearing line span / statement count | | `size.complexity` / `size.nesting` | Decisions and nested control nodes | | `size.parameters` | Explicit parameter count including grouped Go names; Rust `self` receivers are excluded | | `structure.guarded_projection` | Distinct guarded field projections in consecutive local statement/literal regions across all supported languages | | `type.annotation` | Recognized broad/bare Python annotations and forward annotations | | `type.signature` | Missing Python parameter/return annotations | | `type.broad` | Recognized Python typing markers and internal `json.dumps`/pydantic `dump_json`/`model_dump_json` erasure, JS/TS `JSON.stringify` erasure, recognized Go/Java/`serde_json` serializer erasure, TS broad/empty types, Go empty interfaces/`any`, Java `Object`, unbounded wildcards and recognized raw collections, Rust `dyn Any` and `serde_json::Value` paths | | `type.nullable` | Aggregated optional or nullable properties per TypeScript/TSX type declaration and bare nullish fallbacks per innermost function body | | `type.union` | Non-nullish members per TypeScript/TSX union expression after removing `null` and `undefined` | | `type.boundary` | Recognized third-party outputs used without typed ingress conversion | | `unused.parameter` | Declared parameters without resolved read usage | | `unused.function` | Non-exported functions and methods without resolved references | | `unused.field` | Fields without reads; initialization and writes do not count | | `unused.return` | Warning for a known non-void result discarded at a call site | | `test.tautology` | Mirrored positive-equality assertion operands and literal-true assertions (negative and inequality assertions such as `assertNotEqual`, `assert_ne!` and `debug_assert_ne!` are excluded) | | `test.vacuous` | Always-true matchers, assertion-free test bodies and snapshot-only tests (snapshot-only warnings) | | `test.deletion` | Changed-audit baseline comparison: deleted test-file baseline parsing, test declaration multisets, assertion counts against `removed_assertions`, and snapshot path globs | | `flow.swallow` | Wide catch/except handler or `.catch` callback whose subtree contains no re-throw | | `flow.fallback` | `??` chain whose operator count exceeds `max_chain` while every direct default is a bare non-nullish literal | | `type.assertion` | Python typing casts, TS assertions except `as const`, TS non-null assertions, Java reference casts, Rust pointer `as` casts and `std::mem`/`core::mem` `transmute`/`transmute_copy` call sites | | `type.suppression` | Recognized suppression comments, Python no-type-check markers and Rust `#[allow]`/`#[expect]` attributes (including `cfg_attr` forms) | | `imports.wildcard` | Python wildcard imports | | `architecture.owner` | Missing or overlapping configured file owners | | `architecture.structure` | Selected source modules outside their configured owning locations | | `architecture.import` | Literal/normalized dependencies forbidden by project policy | | `architecture.dispatch` | Recognized language/rule identity comparisons and match/switch dispatch | | `architecture.object_model` | Non-underscore module functions in configured `architecture.object_model.paths` extension paths | Complexity starts at one and increments for recognized branches, loops, catches, non-default cases, conditional expressions, comprehension decisions and short circuit operators. Control nesting measures nested recognized control constructs; Python `elif` alternatives share their parent's depth. These are syntax metrics, not compiler CFG metrics; case/exception semantics differ between languages. Formatting/line length remain language-tool checks. Third-party classification uses exact import specifiers in `third_party_modules`; adapters may extend a configured crate root to sub-items imported from that external crate (Rust), while keyword roots (`crate`, `self`, `super`)—including whole-root aliases such as `use crate as api;` or `use crate::{self as api};` (Rust allows a whole-root alias only for `crate`)—stay internal. See [Boundaries, usage and serialization](https://sectrend-cn.github.io/pluvy/docs/serialization-boundaries.md#third-party-boundaries-and-usage) for directional examples and semantic resolution limits. The parser-backed gate is read-only. Checker options are grouped by responsibility; `function_size` owns all five function metrics, `test.integrity` owns `test.tautology` and `test.vacuous`, `flow.handling` owns `flow.swallow` and `flow.fallback`, and `type.contract` owns `type.nullable` and `type.union`. The run-level `test.deletion` owns its single diagnostic outside analyzer registration. Every other checker key matches its diagnostic ID. Only `include` and `exclude` control global file selection. Every checker defaults to enabled; omit default-only entries and `enabled: true`. Reports disclose disabled checker names while findings retain their diagnostic IDs. Malformed configuration and tool failures fail closed. Syntax rejection emits a warning on stderr and permits best-effort checks on the recovered tree. Results may be inaccurate; analyses requiring complete syntax must disclose or qualify unavailable evidence. Python type and import checks use the same recovered tree. Syntax warnings are not defects or configurable checkers and do not change the exit status. Parsing is skipped if all analyzer rules are disabled. Changed modes analyze complete snapshots but report affected definitions and module statements. Function edits include signatures, decorators and bodies; class-header edits select the class. Deletion anchors participate in expansion. Ownership and placement still apply to every changed file. Reports disclose this scope; full audits expose historical debt. Known limitation: an edit inside an existing multi-line class field declaration that does not touch the diagnostic anchor line (the member's first line) loses member-anchored aggregate or multi-line diagnostics in the change modes; `type.broad`, `type.annotation` and `structure.guarded_projection` are lost the same way. Change scopes do not expand class members; use `--all` to audit such edits. Configuration changes require architecture review; neither excluding debt nor increasing limits is remediation. ## Semantic review and delivery evidence The gate cannot prove inferred library types, meaningful unions, generic type relationships, arbitrary alias chains, canonical model ownership, permissive schemas, all serialization boundaries, honest validators, authorization, all dead code, lifecycle safety or logging quality. Review these through the changed call chain, including tests and third-party interfaces. Dynamic imports, escaped module strings, build aliases and compiler resolution need language-aware dependency checks or review. Map requirements and risks to observable assertions. Cover relevant invalid, empty, boundary, retry, cancellation, cleanup and failure cases. Measure statement and branch coverage; inspect missing changed lines and partial branches. Preserve behavioral assertions, fixture ownership and exact test discovery. A percentage alone does not establish adequate tests. Coverage is a separate delivery gate, not implemented by this syntax tool. Before accepting a change, record: - Owners, dependency direction, canonical contracts and any approved exceptions. - Exact formatter/linter/type-checker, architecture and test commands and results. - Requirement/risk-to-test mapping and changed-line/branch coverage evidence. - Known historical debt and unresolved semantic or inference gaps. Never automatically roll back, revert, discard, reset, restore, overwrite or delete existing changes to satisfy a gate. Preserve the state and obtain explicit authority if reversal is necessary. Hooks must not stash or auto-fix. Project publication status and compatibility requirements must be decided explicitly. --- Source: https://sectrend-cn.github.io/pluvy/docs/plugin-architecture.md # Language and rule architecture The architecture uses a common tree-sitter context, independently registered languages and rules, typed grammar capabilities, and application-owned required coverage. This document records the current architecture and its compatibility behavior. ## Ownership and interfaces | Boundary | Owner and contract | | --- | --- | | Language identity | `LanguageDefinition` declares an open identity and suffixes; required rules belong to an application profile | | Parsing | `ContextParser` produces `TreeContext` backed by a concrete tree-sitter `Tree`; `.root` exposes its root `Node` | | Grammar interpretation | Language adapters implement the consuming domain's narrow syntax protocols | | Rule behavior | `RuleBundle` consumes `TreeContext` and declares identity, API version, diagnostic IDs and `RuleRequirements` | | Checker configuration | Owner-local typed fragments declare schemas and identities; `policy.models.Checkers` explicitly composes them | | Application policy | `AnalysisProfile` specifies required diagnostic coverage and explicitly unavailable optional analysis | | Composition | `plugins/builtins.py` connects language adapters, shared rules and language-specific checks | | Execution | `TypedAnalyzer` validates its composition, uses the session's parse and runs enabled bundles | | Session lifetime | `AnalysisSession` owns exact snapshot parsing, reusable semantic evidence and session-scoped adapter instances created by `for_session()` within one execution | | Registration | Language discovery and rule ownership are registered separately; `AnalyzerRegistry` validates composed analyzers | Checker configuration and its compatibility contract are described in [Checker-owned registration](#checker-owned-registration). Required capabilities are explicit. A rule that consumes semantic evidence requires it through `RuleRequirements`; metrics and architecture rules receive their grammar contracts through typed construction. Registration and execution validate availability without inspecting rule identities or concrete rule classes. Validation runs before enable flags can skip analysis, and rules added after analyzer construction cannot bypass capability checks. All language-specific node interpretation stays with language adapters or specific language rules. Shared algorithms retain concrete domain contracts and tree nodes; there are no generic payload dictionaries, casts or secondary Python ASTs. Python annotations and forward annotation expressions are handled with its registered tree-sitter grammar. Parser warnings disclose recovery limitations; infrastructure and required capability failures remain analysis errors. Package placement follows behavior ownership. Shared rules sit with the policy that executes them: metrics in `metrics/`, dependency checks in `architecture/`, and usage and boundary checks in `semantics/`. Language-specific rules live beside the grammar they interpret, and there is no root-level catch-all rule package. Language plugins do not assemble analyzers or select shared rule sets, and shared analysis and rules do not import concrete language plugins. Application composition imports concrete languages and rules, binds them through typed construction and dispatches on no language identity; the CLI and snapshot infrastructure stay outside domain analysis. Snapshot identity includes content and grammar, so staged and working-tree sources never share stale evidence. Conflicting contents for one semantic module within one execution are rejected explicitly, sessions reject a different policy, and a selected source snapshot takes precedence over a reference with the same language and path. Java is registered through the same composition. Its grammar interpretation and type policy live in `languages/java/`; shared engines never import that package. `BindingSyntax.inherited_types` returns `tuple[Node, ...]` so a language can expose multiple independent inheritance clauses. Custom semantic adapters must return an empty tuple when there are no bases. Java's checked scope and resolution limits follow the shared per-checker coverage in [checker configuration](https://sectrend-cn.github.io/pluvy/docs/checker-configuration.md). Rust follows the same composition under `languages/rust/`. Its semantic adapter analyzes each `.rs` file independently (`package()` returns the file path, `module_names` uses the extension-stripped file path, `import_target()` links only keyword-rooted imports to file-level declarations in the same file rather than linking non-keyword external crate imports to a sibling local `.rs` file, and `interop_group()` returns `"rust"`, isolating Rust from other languages' unresolved member reads, module names, same-package lookups and parameter-property auxiliary indexing). Within a single file, it attaches only directly declared inherent methods to an `impl` type, resolves `self` receivers and associated functions (including `Self::new()`) against that `impl` type, and replaces `Self` only when an annotation spells bare `Self` or a reference form such as `&Self`, `&mut Self` or `&'a Self` (wrapped forms such as `Wrap` and `Option<&Self>` keep their outer type as written). It binds pattern introducers (`let`, `for`, `while`, `loop`, `if let`, `match` arms, closures) as lexical declarations through the shared `sequential_scope`, `scope_exterior` and `hoisted` hooks: same-scope `let`, `if let`, `while let`, `let`-`else`, `let` chains with binding leaves, and `match` arms whose guard contains a `let` condition open sequential scope regions visible only to subsequent siblings and guarded branches (with `captured_pattern` bindings such as `let y @ Some(x) = d else { return; };` entering the same region and plain `let` initializers staying in the enclosing scope); `scope_exterior` places `for` iterables, the first `let` value of an `if let`/`while let` chain, `if` `else` branches and item name nodes (`fn`, `struct`, `enum`, `trait`, `union`, `mod`) in the enclosing scope before the node's own bindings so `crate::h` and aliases resolve to the function symbol rather than a same-named parameter; and `hoisted` keeps inner items visible across the block (see [`unused.parameter`](https://github.com/sectrend-cn/pluvy/blob/main/.agents/skills/pluvy/references/checkers/unused.parameter.md)). It treats `const_item`/`static_item` in any scope as non-fields, and counts fields of `#[derive]` items (including single-level `#[cfg_attr(..., derive(...))]`), fields whose declared type's final path segment is `PhantomData`, and non-wildcard struct pattern bindings as read. Single-file name resolution resolves only keyword-rooted paths (`crate::`, `self::`, `super::`) whose intermediate segments descend through inline `mod` declarations in the same file, plus `use` aliases rooted at those paths. Unconfirmed keyword-rooted paths fall back to `ModuleUses.unresolved` (keeping same-named declarations reachable), and unconfirmed type annotations withhold type evidence (`None`) so member reads stay unresolved rather than mis-binding to a same-named local type. In lexical lookup (`_visible_binding`), value bindings and `use` aliases compete innermost scope first up to the innermost `mod` boundary, with visible `let` bindings outranking hoisted items and `use` aliases, while type-only items (`struct` with braces, `type`, `enum`, `trait`, `union`, `mod`), `extern crate`, type-only `use` aliases and `impl`/`trait` associated `fn` declarations stay out of value resolution (`binds_value=False`). Conditional compilation (`#[cfg]`) is not evaluated and macro bodies remain untyped token trees; exact resolution boundaries and conservative fallbacks are recorded in [Rust name-resolution known limits](#rust-name-resolution-known-limits). Session-scoped adapter instances are created through `for_session()`. `AnalysisSession` caches one session-scoped instance per composed adapter instance by object identity (holding the composed instance so dataclass-derived adapters work without custom equality handling), calling `for_session()` once per composed adapter per session. `RustSemanticSyntax.for_session()` returns a fresh instance per `AnalysisSession` whose `ModuleUses`, `ImportEvidence`, renamed/aliased type-name (`_renamed`) and expanded `use`/declaration (`_expanded`) caches are plain dictionaries keyed by snapshot root (`context.root.id`) and released with the session, while the composition-time instance holds no per-snapshot evidence. Semantic alias target lookup reuses `ImportEvidence.aliases`, and lexical binding competition (`bindings._visible_binding`) receives the session's `ImportEvidence.values` instead of re-expanding `use` declarations directly. `_expand_use` is held only by `languages/rust/imports.py` (snapshot-cached declaration expansion), `languages/rust/consumed_fields.py` (`RustConsumedFields`) and `languages/rust/syntax.py` (`RustImports`), expanded once per snapshot per holder; `languages/rust/modules.py` and `languages/rust/semantic_syntax.py` do not hold or call `_expand_use`. `exported` keeps `pub`/`pub(crate)`/`pub(super)` items, attributed items, trait and trait-impl methods, root `fn main` outside `lib.rs`, and `ModuleUses` reachability, while `implicit_use()` exempts `_`-prefixed names, matching rustc's dead-code conventions. Rust registers no failure-flow rule because it has no exception handlers. Shared semantic analysis exposes eight narrow adapter hooks with safe defaults on `SemanticNodes` so existing languages retain unchanged behavior: `BindingSyntax.sequential_scope(node)` defaults to `False` (when `True`, a declaration, `let` condition/chain with binding leaves, or `match_pattern` whose guard contains a `let` condition opens a new scope region so its targets become visible only to subsequent siblings and guarded branches); `BindingSyntax.scope_exterior(node)` defaults to `()` (subtrees inside a scope-owning node placed in the enclosing scope before the node's own bindings, including in Rust `for` iterables, the first `let` value of an `if let`/`while let` chain, `if` `else` branches and item name nodes); `BindingSyntax.hoisted(node)` defaults to `False` (items declared in the enclosing block scope across sequential regions); `BindingSyntax.binds_value(node)` defaults to `True` (a declared name is visible to bare value references; Rust returns `False` for associated functions inside `impl`/`trait` bodies, for `extern crate` declarations—with or without an alias—and for `use` imports whose in-file target is type-only, so `SemanticIndex.lookup(name, scope, value=True)` skips them for value references while type references and path roots via `in_annotation` still resolve, with `tests/test_value_binding_names.py` guarding unchanged behavior across the six other built-in analyzers); `SemanticSyntax.configured_import(entry, context)` defaults to exact module matching (`entry.module in context.policy.third_party_modules`), letting Rust keep keyword roots (`crate`, `self`, `super`, including whole-root aliases) internal while extending a configured external crate root to its imported sub-items; `SemanticSyntax.for_session()` defaults to returning `self` for stateless adapters while letting stateful adapters keep per-snapshot caches inside the active `AnalysisSession`, cached by composed adapter instance identity; `SemanticSyntax.interop_group()` defaults to `""` (sharing the legacy cross-snapshot namespace so Python, Go, Java, JavaScript, TypeScript and TSX retain unchanged behavior, keeping JS, TS and TSX interoperable across relative imports and member reads in one group), while Rust returns `"rust"` so `ProjectUsage.modules` (keyed by `(group, name)`), same-package peer lookups, `UsageEvidence.unresolved` (`evidence.uncertain(group)`) and parameter-property auxiliary indexing (constructed per `interop_group()` only for groups that have a `parameter_property_syntax()` provider, namely the default `""` group when a TypeScript/TSX snapshot is present, while skipping `"rust"`) never cross between Rust and any other language (`tests/test_interop_groups.py` guards this isolation); and `BindingSyntax.result_type(node, declared)` separates a function's declared result from its type evidence. `BindingSyntax.result_type(node, declared)` defaults to returning `declared` itself. A function's `Symbol.annotation`/`annotation_text` keep the result it declares, which the result contracts (`has_result`, `call_result`, `concrete_result`, the typed-converter reading in boundary evidence, and `unused.return`) read as proof that a call yields a value; `Symbol.result_type` is the evidence the index derives the function's `type_name` and `class_scope` from, and `Symbol.type_evidence()` returns it for a function and `annotation` for every other declaration. The index calls the hook only when a result is declared, so an undeclared result never has type evidence. Rust does not follow type alias chains: it returns `None` when the declared result's outer type (looking through `&`/`&mut` and generic wrappers) is a qualified path that cannot be confirmed to a directly declared type (`struct`, `enum`, `union` or `trait`) through this file's inline `mod` declarations (a terminal supplied only through a `pub use` / glob re-export, or matched only by a same-named `fn`, `const`, `static` or `mod`, gives no type evidence and stays unconfirmed), confirms to a `type` alias, or uses a bare name declared as a `type` alias or `use … as` rename in the same file (`Self` is substituted only for bare `Self` and reference forms such as `&Self`, `&mut Self` and `&'a Self`, leaving wrapped forms such as `Wrap` and `Option<&Self>` as written). Member reads on such a result stay unresolved instead of binding to a same-named in-file type, while discarded-result warnings and typed-converter classification remain unchanged; `tests/test_result_type_evidence.py` guards unchanged behavior across the six other built-in analyzers. ### Rust name-resolution known limits Twelve known Rust name-resolution, macro and changed-scope limits apply (user-visible entries are also summarized in the skill checker index and on affected checker pages): 1. **Single-file analysis and keyword-rooted paths.** Each `.rs` file is analyzed independently: out-of-line modules (`mod child;`, `#[path = "..."] mod name;`), cross-file `crate::…` paths, `pub use` re-exports, glob imports (`use m::*;`), `extern crate self as name;` and leading `::` absolute paths are not followed across files, and non-keyword external crate imports never link to sibling local `.rs` files. Only keyword-rooted paths (`crate::`, `self::`, `super::`) descending through inline `mod` declarations in the same file resolve to their target declaration; unconfirmed keyword-rooted paths place their final segment in `ModuleUses.unresolved` (keeping same-named declarations reachable). Leading `::`-prefixed paths do not receive that exemption (false-positive limit for `::api::work()` under `extern crate self as api;`). Bare calls imported via a glob resolve lexically innermost-scope-first rather than entering `ModuleUses.unresolved`: if an enclosing module declares a same-named private function nearer than the glob's source, the call binds to the nearer item (false positive on the glob source, false negative on the nearer item; an explicit `use` resolves accurately, and unused siblings across multiple modules declaring `pub fn hidden` are not reported). 2. **Files declaring an out-of-line module.** Whenever a file contains `mod child;`, private functions and methods declared at file root or inside inline `mod`/`impl`/`trait` bodies, as well as all `struct` and `union` fields (including `pub`), are not reported. Nested functions and named closures inside function bodies remain candidates. 3. **Conditional compilation is not evaluated.** Every `#[cfg(…)]` and `#[cfg_attr(…)]` item (including `#[cfg(any())]`, `#[cfg(test)]` and feature predicates) is treated as enabled, and nested `#[cfg_attr(..., cfg_attr(...))]` attributes are not expanded recursively. When `cfg`-gated same-named items coexist in one container, keyword-rooted paths bind to the **first** declaration in source order (which can shift `unused.function` or `unused.return` findings). 4. **Type aliases and unconfirmed type paths are not followed.** Parameter or return annotations written with a local `type` alias, a `use … as` rename, or a qualified path not confirmed to a directly declared type (`struct`, `enum`, `union`, `trait`) through this file's inline `mod` declarations (including re-exported terminals or terminals matched only by a same-named `fn`/`const`/`static`/`mod`) provide no type evidence (`None`): member reads stay unresolved by member name rather than mis-binding (and qualified or renamed `serde_json::Value` callback parameters do not report `type.boundary`, while `type.broad` still reports them). `Self` resolves to the `impl` type only for bare `Self` and reference forms (`&Self`, `&mut Self`, `&'a Self`, `&&Self`), leaving wrapped forms such as `Option<&Self>` as written. 5. **Member reads with unknown receiver type.** When a receiver's type cannot be determined (generics, trait objects, pattern bindings, or `.name`/`::name` tokens inside macro arguments), the member name is treated as read across Rust files only and **never affects files in other languages**. 6. **Same-scope value and type collisions.** Within one scope, a function shares a single symbol slot with a same-named `mod`, type, `extern crate` or type-only `use` (later overwrites earlier); raw identifiers `r#p` and `p` are distinct names; and block-local type items (`struct`, `enum`, `trait`, `union`, `mod`) plus associated `const` items still participate in bare-name lookup. 7. **Macros.** Macro bodies are not expanded. `macro_rules!` definition bodies are skipped completely by read collection (so fields or functions referenced only inside a definition body can still be reported), whereas `.name` and `::name` tokens inside macro invocation arguments contribute unresolved member reads under limit 5. For any macro invocation, inline `{name}` captures and named format width/precision parameters (`{v:width$}`, `{v:.decimals$}`, skipping `}` fill before alignment) count as reads of the visible value binding without subtracting explicit `name = …` arguments (under-reporting an unused `p` in `println!("{p}", p = 7)`); on the serialization side, named width/precision parameters are not captures and `}`-fill skipping is not enabled. Format and print macros (`println!`, `print!`, `eprintln!`, `eprint!`, `format!`, `format_args!`) are matched solely by final path segment without modeling `macro_rules!` shadowing (their `name = …` labels are not counted as reads). Macro names—bare or qualified at any depth—stay in the macro namespace at every path segment and never count as value reads, unresolved member reads, call targets or `ModuleUses.unresolved`, while reads inside macro arguments stay unaffected. 8. **Assertion macro recognition.** `assert!`, `assert_eq!`, `assert_ne!`, `debug_assert!`, `debug_assert_eq!` and `debug_assert_ne!` are recognized by final path segment (`std::` and `core::` prefixes match as well); locally redefined macros with those names are not distinguished. 9. **`unused.return` scope.** Discarded-result warnings inspect only the written return annotation (or proven value body) without modeling `async`, `#[must_use]` or type-alias targets: discarding an unannotated `async fn` `Future` or unannotated `#[must_use]` result is not reported, whereas a unit return written through a type alias (`type U = (); fn f() -> U`) still warns. 10. **Callable spellings and alias depth.** Parenthesized `transmute` calls (`(std::mem::transmute)(x)`) are not matched by `type.assertion` (which requires a direct identifier or path callee), whereas path spelling unwraps parentheses for serialization checks. Separately, value alias chains exceeding the 64-step path-spelling budget (counting each syntax unwrap and alias hop) yield no resolved path spelling, so path-based `type.broad` and `type.assertion` findings stop reporting once the budget is exhausted. 11. **Extreme syntax nesting.** Deeply nested expressions or blocks (roughly 300+ levels) exceed the interpreter recursion limit and fail the run with exit code 2. This limit is shared across all seven built-in analyzers. 12. **Changed-mode diagnostic scope (`--base` / `--staged`).** Every direct item declared inside an `impl`, `trait` or inline `mod` body (excluding comments and outer attributes—including methods, functions, associated `const`/`type`, `static`, multi-line `use` and `struct` declarations) is an independent incremental unit; editing a block header (through its opening `{` line and trailing comment) selects the whole block; editing only an outer attribute line (such as `#[test]` or `#[repr(C)]`) or standalone doc-comment line above an item does not select the item (use `--all` or edit the item itself); top-level items outside those blocks follow the shared root-statement and header rules. Offline verification and corpus boundaries: Pluvy runs offline on tree-sitter grammars without invoking `rustc`, `cargo` or external crate registries; real third-party crate corpora are analyzed offline against static source snapshots, and fixtures referencing external crates or unstable syntax cannot be compiled standalone. ## Shared alias and output analysis `semantics/aliases.py` owns stable callable/module alias resolution and constructor provenance. `NameSyntax` supplies transparent grammar expressions, imported-name identity and recognized built-ins. Resolution uses the canonical semantic index; cycles, shadowing and multiple assignments do not become guessed destinations. `semantics/flow.py` owns single-assignment carrier and container forwarding. Its `Destinations` protocol classifies a use as permitted, rejected or requiring further traversal. Both third-party boundary evidence and serialization checks use this same algorithm. An internal use cannot be hidden by another permitted output use. `semantics/failure.py` owns the separate `builtin.failure` policy bundle, which reports swallowed wide captures and coalescing chains that hide failures behind literal defaults. It shares no traversal or evidence with `semantics/flow.py`, whose carrier forwarding serves encoding output proof. `EncodingRule` consumes `EncodingSyntax`, which defines `member_encoder` for receiver-agnostic member recognition and also identifies qualified encoders, decoders, argument consumers and actual output APIs. `GrammarEncoding` provides the default `member_encoder` implementation backed by its `member_encoders` set. A structural `EncodingSyntax` implementation that does not inherit `GrammarEncoding` must define `member_encoder` itself; registration does not validate protocol members, and a missing definition fails closed during analysis with an `AnalysisError` such as `Rule bundle … failed: '…' object has no attribute 'member_encoder'`. The `argument` capability on `EncodingSyntax` returns the canonical `ParameterSlot` for a payload; this lets shared semantics enforce configured positional/keyword output selectors without reading grammar fields. `BroadTypeOptions.encoding` owns validated additive encoder, decoder and output API declarations, including the restricted `*.member` encoder form. Explicit decoder evidence wins over configured output matches. A decoder rejection takes precedence over a configured library-input exemption. Grammar/API interpretation lives in `languages/`; shared semantic code imports no concrete language or grammar and contains no language-name dispatch. Application composition supplies Python, Go, Java, Rust and JavaScript adapters. Their type-rule objects receive an `EncodingRule` through their constructor and retain ownership of their combined `type.broad` diagnostics; JavaScript registers that rule directly. This keeps diagnostic ownership unique. Custom construction of `PythonTypeRule`, `GoTypeRule`, `JavaTypeRule`, `RustTypeRule` or `TypeScriptTypeRule` must supply the encoding rule explicitly. They reuse the session's existing context and boundary index. Current serializer adapters cover Python `json.dumps` plus pydantic `dump_json`/`model_dump_json` member names, JavaScript/TypeScript/TSX `JSON.stringify`, imported Go JSON Marshal/MarshalIndent, selected imported Gson/Jackson Java serializers and Rust `serde_json` `to_string`/`to_string_pretty`/ `to_vec`/`to_value` paths (spelled through `use` aliases or directly). Exact scoped instance outputs are available in Python, Go, Java, JavaScript, TypeScript and TSX; Rust does not recognize instance outputs. Java interprets invocation nodes and functional-interface fields; Go supplies the proven first payload binding of a byte/error result; Rust spells qualified paths through `RustPathNames` and recognizes `println!`/`print!`/`eprintln!`/ `eprint!` arguments, receiver-proven `std::io::stdout()`/`stderr()` and `Result`-unwrapped `std::fs::File::create(...)` `write_all`/`write` calls, and `std::fs::write` payloads as terminal outputs without treating arbitrary `Write` calls, memory buffers, containers or derived values as outputs. Shared flow checks that binding's every read and leaves sibling error results independent. Exact supported signatures and conservative limits are documented in [Serialization boundaries](https://sectrend-cn.github.io/pluvy/docs/serialization-boundaries.md#source-owned-instance-output-callbacks). ## Shared guarded projection analysis `GuardedProjectionRule` consumes the language-owned `ProjectionSyntax` capability and existing session semantic index. `semantics/projection/` owns checker options, binding identity, candidate evidence and consecutive-region clustering. `languages/projection_syntax.py` shares the grammar operations, and each language supplies its predicate and construction interpretation through `ProjectionSyntax`. Language code cannot import the projection rule implementation; shared matching imports no language implementation and selects no language identity. Built-in composition requires this diagnostic for Python, Go, Java, JS, TS, TSX and Rust, and a new language must supply equivalent adapters and behavioral tests before claiming coverage. Exact syntax coverage and conservative limits are documented in [the guarded projection checker reference](https://github.com/sectrend-cn/pluvy/blob/main/.agents/skills/pluvy/references/checkers/structure.guarded_projection.md). ## Changed-scope capability `Source.changed_lines` is `None` for a full audit and a concrete frozen set for changed snapshots, including deletion anchors. Built-in analyzers receive a `ScopeSyntax` adapter through `TypedAnalyzer.scopes` (Rust registers `RustScopes` in `languages/rust/change_scopes.py`, overriding `definition` and `header_end` for direct items inside `impl`/`trait`/inline `mod` bodies; see [Rust name-resolution known limits](#rust-name-resolution-known-limits) limit 12). The shared `AffectedScopes` consumer expands edits using grammar-owned definition extents and class headers, then filters emitted diagnostics. It never truncates the parsed snapshot or semantic evidence. Rules declare file-level obligations with `Finding.scope="file"`; the default is `"line"`. Ownership and placement use file scope, without rule-ID dispatch in the shared filter. Custom `TypedAnalyzer` compositions must supply this capability for changed-scope runs; missing capability fails visibly instead of silently claiming scoped checks. Full-source library calls remain compatible with the default `Source` constructor. ## Run-level deletion gate `TestDeletionGate` in `semantics/testing/gate.py` is a run-level execution shape, not a `RuleBundle`. It consumes the baseline evidence ports supplied by the CLI and the narrow `BaselineParsing` protocol, whose `TestBinding` pairs a `ContextParser` with the same `TestSyntax` used by `TestIntegrityRule`. The gate itself imports no snapshot, language or plugin module: reading baseline blobs belongs to `snapshots.py`, and parser/syntax assembly belongs to application composition. `plugins/builtins.py` exposes `builtin_deletion_gate()`, symmetric with `builtin_registry()`. It iterates `builtin_languages()`, attaches each plugin's parser, and selects the matching `TestSyntax`; TypeScript and TSX reuse `JavaScriptTestSyntax`, and Rust binds `RustTestSyntax`, whose candidates are `#[test]` (and `*::test`) functions whose file matches the shared test paths (the default globs cover `tests/*` and `*/tests/*`, so inline `#[cfg(test)] mod tests` modules under `src/` are not checked by `test.integrity` or `test.deletion` unless those source paths are added to `paths`). The private bindings container implements `BaselineParsing`. Gate bindings are fixed to the built-in language set: a custom `AnalyzerRegistry` passed to `main(..., analyzers=...)` does not participate in gate composition, so a deleted file in a language outside that set is selected from the diff but has no binding and is skipped silently. The gate is not registered by any analyzer, so `AnalysisProfile.required_rules` does not apply to it; this is a deliberate, documented exception for run-level checks. Its single diagnostic remains part of the policy switch, and `enabled: false` skips the gate. `cli.py` invokes the gate only for `--base` and `--staged`. It reads changed paths, asks the gate for current changed test candidates, reads their baseline blobs, collects deleted-file baselines, then merges the returned findings with analyzer findings under the same sort key. `--all` never activates the gate. Deleted files are not analyzed inputs, so report `files` counts current selected sources only; deletion findings are file-scoped and anchored at line 1, column 1. Infrastructure failures such as an unmerged staged index or a non-UTF-8 baseline blob fail closed through the existing CLI error path. ## Extending the application A shared rule consumes the same concrete context regardless of source language: ```python @dataclass(frozen=True) class ModuleSizeRule: name: str = "project.module_size" api_version: int = 2 requirements: RuleRequirements = RuleRequirements() rule_ids: tuple[str, ...] = ("project.module_size",) def check(self, context: TreeContext) -> tuple[Finding, ...]: if context.root.named_child_count <= 100: return () return (Finding(path=context.source.path, line=1, column=1, rule="project.module_size", message="Split module responsibilities"),) ``` This example bounds top-level named syntax nodes; their meaning is grammar-defined. A rule requiring a normalized concept such as executable statements must consume the appropriate typed syntax capability instead of assuming identical node shapes. `builtin_analyzers()` returns concrete `TypedAnalyzer` objects. Extend their `bundles` before registering them in an `AnalyzerRegistry`. Use `builtin_registry()` for the standard application composition. Pass the same registry to discovery and execution; `cli.main(arguments, analyzers=registry)` provides that integration. Rules do not declare a list of language identities. Applicability and grammar capability bindings belong to application composition. For a new language, declare its identity, suffixes, grammar and adapters; build an application profile and compatible rule bundle registry; then compose and register its analyzer. The count-dialect fixture in `tests/test_extensions.py` uses a registered tree-sitter grammar and verifies discovery, CLI findings, source selection and session lifetime through the same public extension path. ## Compatibility and failure behavior Extension contracts are defined over the common tree context rather than a language-specific one: - Extensions consume the shared `TreeContext`. - `ContextParser`, `RuleBundle`, `BundleRegistry` and `TypedAnalyzer` take no arbitrary context type parameters. - Rules declare capabilities through explicit requirements; applicability and grammar capability bindings belong to application composition. - Language plugins do not assemble analyzers; built-in assembly is application-owned. - `AnalysisProfile.required_rules` declares required diagnostic coverage. - Custom analyzers provide `validate()`, `needs_semantics(policy)` and accept an optional execution session; they expose a typed optional `semantic_binding`, which registration attaches automatically, and remain responsible for their declared contract and failures. The configuration schema and the extension API are separate compatibility boundaries. Registration rejects legacy-shaped extension objects, ambiguous suffixes, invalid identities, missing required coverage and conflicting rule ownership. Undeclared findings and executing plugin failures still fail closed. Disabled bundles do not execute; disabling all rules avoids parsing after composition validation. Required coverage remains independent of checker enable flags. Analysis runs on tree-sitter recovery and checks over the available syntax. A custom parser that raises `SyntaxFailure` supplies `tuple[ParseWarning, ...]` and must explain in its warnings which dependent checks are unavailable. Recovery differences must remain tested and documented. Source selection stays snapshot-based and gate execution stays read-only. ## Checker-owned registration `Checkers` explicitly composes typed configuration fragments. It declares no checker fields or checker-name list itself. Owners declare their concrete options, configuration key and diagnostic mapping beside the associated checker contracts: | Owner | Configuration | | --- | --- | | Function measurements | `metrics/options.py` | | Architecture checks | `architecture/options.py` | | Serialization checks | `semantics/encoding_options.py` | | Boundary and usage checks | `semantics/options.py` | | Shared type and syntax switches | `policy/type_options.py` | `policy/contracts.py` owns strict, frozen base contracts and `CheckerDefinition`. Each fragment declares concrete Pydantic fields, derives JSON aliases from its checker definitions, and contributes `CheckerState` values through cooperative `checker_states()` composition. A state contains only identity, diagnostic mapping and an enable flag. Option payloads remain in their original concrete fields; there is no heterogeneous option store, cast, dynamic model or serialization step. `disabled_checkers()` and `disabled_rules()` consume those states uniformly. `function_size` declares its five diagnostic IDs at its owner; it needs no special branch in shared policy code. Rule implementations and built-in requirement profiles reference the same definitions. Validation rejects duplicate names, empty/duplicate diagnostic IDs, overlapping diagnostic ownership and differences between registered checker names and the composed schema's field aliases. A new checker contributes a typed fragment and adds that fragment to the explicit application composition. Its schema, defaults and disabled-diagnostic expansion then participate automatically. Runtime discovery of arbitrary checker schemas is outside this API. Each overriding `checker_states()` must include `super().checker_states()`; the field-registration invariant rejects omissions. Policy JSON, the Python option constructors (for example `BroadTypeOptions(encoding=EncodingOptions(...))` inside `Checkers(type_broad=...)` and `CheckerOptions` for checkers without extra settings) and imports from `policy.models` are supported. That module owns composition and re-exports canonical option classes rather than defining them. Package-level `MetricRule` and `ArchitectureRule` exports load their concrete implementations lazily, so importing checker contracts does not create an execution-to-policy import cycle. `policy/contracts.py` holds the leaf contracts and imports no application modules. The composition module imports owner contracts, and runtime checkers consume their owner's definitions and concrete policy fields. --- Source: https://sectrend-cn.github.io/pluvy/docs/go-consumed-fields.md # Go implicit field consumption Go structs are often read through reflection, serialization or structural comparison rather than explicit `value.Field` expressions. To avoid false `unused.field` findings while still flagging genuinely unread fields, the Go semantic adapter contributes recognized implicit reads to shared `contract_reads`, keeping shared usage analysis independent of concrete language implementations. `GoConsumedFields` owns recognized consumers and visibility/tag/custom-marshaler rules; `GoValueOrigins` retains source ownership while following concrete values, package members, aliases and actual generic call arguments. Recognized consumers are imported JSON/XML `Marshal`, `MarshalIndent` and encoder `Encode`, `reflect.DeepEqual`, Kubernetes `DefaultUnstructuredConverter.ToUnstructured`, and structural equality/inequality (`==` / `!=`). Serialization skips private named fields and exact `-` tags. Custom marshal methods prevent blanket storage-field consumption. Equality does not traverse pointer targets; `DeepEqual` does. Anonymous struct embedding permits traversal to exported nested fields. Behavioral coverage is verified in [tests/test_go_consumed_fields.py](https://github.com/sectrend-cn/pluvy/blob/main/tests/test_go_consumed_fields.py) and [tests/test_go_consumption_regressions.py](https://github.com/sectrend-cn/pluvy/blob/main/tests/test_go_consumption_regressions.py). The implementation is a parse-based evidence analysis, not the Go compiler or a full implementation of `encoding/json` field selection. `GoSerializationFields` selects fields by wire name and embedding depth, rejects ambiguous peers, honors JSON tagged dominance, decodes interpreted Go tags and recognizes uniquely promoted marshal methods. Exact custom-method signatures, pointer method-set/addressability distinctions, XML namespace/path/attribute conflict rules and generic stored-parameter substitution remain unresolved. Package lookup uses selected snapshot directory suffixes; module replacements and build constraints are not compiler-resolved. Runtime interface flows and arbitrary returned generic values are not fully inferred. --- Source: https://github.com/sectrend-cn/pluvy/blob/main/examples/.pluvy/pluvy.json # Example .pluvy/pluvy.json ```json { "version": 2, "include": ["src/*", "tests/*"], "exclude": [], "checkers": { "type.broad": { "encoding": { "encoders": ["orjson.dumps"], "decoders": ["orjson.loads"], "outputs": [ {"call": "transport.publish", "arguments": [1], "keywords": ["body"]} ] } }, "function_size": { "lines": 50, "statements": 50, "complexity": 10, "nesting": 3, "parameters": 5 }, "architecture.owner": { "owners": [ {"name": "domain", "paths": ["src/domain/*"]}, {"name": "application", "paths": ["src/application/*"]}, {"name": "adapters", "paths": ["src/adapters/*"]}, {"name": "tests", "paths": ["tests/*"]} ] }, "architecture.import": { "boundaries": [ { "name": "domain does not depend on adapters", "sources": ["src/domain/*"], "forbidden_imports": [ "adapters", "adapters.*", "src.adapters", "src.adapters.*", "src/adapters/*" ] } ] }, "architecture.object_model": {"paths": ["src/domain/rules/*"]} } } ``` --- Source: https://github.com/sectrend-cn/pluvy/blob/main/.agents/skills/pluvy/SKILL.md --- name: pluvy description: Run the pluvy gate after code tasks only in repositories with a project policy or an explicit project requirement, or when the user explicitly requests a run. Use also to adopt, install, configure or explain pluvy, edit `.pluvy/pluvy.json`, triage findings, inspect checker coverage and options, or use approved line suppression with a reason in every supported language. A global installation or skill availability alone does not enable a repository; without adoption or an explicit run request, skip the run and the gate notice. --- # pluvy pluvy is a parse-based architecture policy gate: it audits this repository's sources against the policy in `.pluvy/pluvy.json` and reports findings. ## Decide whether the gate applies Check the target repository (the explicit `--root`, or the repository being worked on). The gate applies when at least one is true: - The repository has `.pluvy/pluvy.json`. - Project instructions, scripts or CI explicitly require the gate, including a policy selected through `--config`; use that project's root and config path. - The user explicitly requests a gate run for this task. If none applies, stop silently: do not run the gate, create a policy, suggest setup, or include a skipped, missing-config or "not counted as passed" gate notice in the task report; continue the project's own checks. A globally installed executable, a discoverable skill, an example policy or a skill pointer alone does not enable the gate, and the CLI must not be run just to test adoption. Non-adoption is silent; failure is not. When the gate applies, missing configuration is a failure, and an invalid or unreadable policy is a failure: keep the CLI's exit-code semantics and never skip silently. This skill also covers adoption, installation, configuration, explanation and triage when requested, even before adoption; loading it for those purposes neither requires a gate run nor authorizes creating a project policy. ## Gate policy (binding) 1. `After completing a code task in a repository where the gate applies, run the pluvy gate before reporting the task done, and report the mode, exit code and findings truthfully.` 2. `When the gate applies, never claim it passed when it was not run, failed with exit code 2, or the tool is not installed; state the reason explicitly instead. When it does not apply, omit gate execution and reporting.` 3. `Do not add suppressions or weaken the policy to make the gate appear green; policy changes require a separate full audit and review.` ## Post-task gate commands | Situation | Command | Notes | |---|---|---| | Task changes are uncommitted | `pluvy --base HEAD` | Working tree vs HEAD, untracked included (new files get a full audit) | | The task produced commits | `pluvy --base ` (the parent of the task's first commit) | On a clean tree `--base HEAD` audits 0 files and exits 0 — a false pass to avoid | | Task start commit unknown | `pluvy --all`, and state that this is a full audit that may include pre-existing debt | Prefer over-reporting to under-reporting | | `--staged` | Not used for post-task gating | Reads index blobs only, which does not match the agent workflow boundary | Canonical commands: ```sh pluvy --all pluvy --staged pluvy --base pluvy --root /path/to/project --all pluvy --all --format json ``` `--root` defaults to the current directory (Git modes require the repository root); `--config` defaults to `.pluvy/pluvy.json`, resolved relative to the root. ## Exit codes | Exit code | Meaning | |---|---| | `0` | No error-severity findings (warnings do not affect it) | | `1` | Error-severity findings are present | | `2` | Configuration/encoding/filesystem/Git failure (including `--staged` while a policy change is staged) | ## Post-run checks 1. The gate output ends with a line like `Architecture base: N files; M findings.`. If N is 0 while the task really changed code, the base choice is wrong: reselect it and rerun; do not treat the run as a pass. 2. If the task changed the policy file, judge it with a separate `pluvy --all`, not a `--base` run alone, and have the policy change reviewed. 3. Unrelated dirty changes that predate the task are swept into `--base HEAD` runs: list them truthfully; do not filter them silently. 4. When a repository contains mixed-language directories (for example Rust alongside Python, Go, Java or JavaScript/TypeScript files), run and accept the gate on the mixed-language directory in one session rather than testing each language in isolation, so cross-language isolation and selection match real runs. ## Report format Applies only when the gate applies. Report the mode, the exit code and the findings (error/warning counts plus key items). If an applicable gate was not run, exited with code 2, or the tool is not installed, state that explicitly — never report the task as gated or passed. Where the gate does not apply, omit gate status entirely. Test-suite execution and its reporting stay independent of gate applicability. ## Triage 1. Fix the code first: findings are evidence of policy violations. 2. A standalone next-line suppression comment naming the exact rule id is allowed, in every supported language, only for an exception explicitly approved by a human beforehand; the written reason only records that approval. Use the language's own line-comment marker: `#` in Python, `//` in Go, Java, Rust and the JavaScript family. Block-comment forms, wildcards, lists, `type.suppression` itself and a missing reason are invalid and report `type.suppression`. Syntax and validation rules: [approved next-line diagnostic exceptions](references/comment-suppressions.md). 3. Policy changes (thresholds, excludes, owners, boundaries, enable flags) are architecture decisions: they require a separate `--all` full audit and review. Never weaken the policy to force a green report (policy item 3). ## Capability boundaries and language support The gate parses the selected sources with tree-sitter, collects syntactic evidence and applies the policy. What it does not do: - It does not infer types: broad markers, annotations and conversions are syntactic evidence, not resolved types or compiler proofs. - It does not resolve package aliases, build-system aliases, dynamic imports, reflection or computed members, and it does not prove runtime ownership or which implementation a call reaches. - It does not detect all unused code, prove validators or logging safety, or measure coverage; unused findings describe the checked snapshot view and unresolved external usage, not a repository-wide proof. - It is not a linter, formatter, type checker or coverage tool: keep the language formatter, type checker, tests, branch coverage and semantic architecture review as separate required checks. - JavaScript and JSX carry no type annotations: type safety needs a configured type-aware checker, while usage, boundary and encoding analysis still run on those files. - Rust analysis is single-file only: it resolves `crate::`, `self::` and `super::` paths only through inline `mod` declarations in the same file, does not evaluate `#[cfg(...)]` predicates or follow type aliases or cross-file modules, and treats unknown keyword-rooted paths and unconfirmed type annotations conservatively (not reporting rather than guessing). Rust uses its own interop group so its unresolved member reads and module names do not affect the six other built-in analyzers in mixed-language directories. - A passing syntax gate does not certify compliance with every policy rule. Seven analyzers cover six languages (including JSX and TSX syntax): | Analyzer | Source suffixes | |---|---| | Python | `.py`, `.pyi` | | Go | `.go` | | Java | `.java` | | JavaScript and JSX | `.js`, `.jsx`, `.mjs`, `.cjs` | | TypeScript | `.ts`, `.mts`, `.cts` | | TSX | `.tsx` | | Rust | `.rs` | Selection and enablement: - Every checker is enabled by default for every selected file; `enabled: false` turns one checker off for all selected files, and there is no `enabled` flag scoped to one language or one file. - The global `include` and `exclude` lists drop files from every checker at once, except that changed snapshot paths reported by the run-level `test.deletion` gate follow the changed set instead ([its checker page](references/checkers/test.deletion.md)). - Architecture `placements`, `boundaries` and `paths` (under `architecture.object_model`) only select where that one architecture check applies. - `owners` is not a file selector: once owners are configured and the checker is enabled, every selected file must match exactly one owner, so an unmatched or doubly matched file is a finding. Coverage does not promise complete evidence for every construct: resolution limits for boundaries, usage, encodings and guarded projections are recorded on the corresponding checker pages and remain review obligations. ## Checkers and per-language coverage The schema has 22 logical checkers, which produce 29 built-in diagnostic IDs. `function_size` owns the five `size.*` IDs, `test.integrity` owns `test.tautology` and `test.vacuous`, `flow.handling` owns `flow.swallow` and `flow.fallback`, and `type.contract` owns `type.nullable` and `type.union`; the run-level `test.deletion` owns its single diagnostic outside analyzer registration, and every other checker name matches its diagnostic ID. | Checker | Reports | Languages | |---|---|---| | [`structure.guarded_projection`](references/checkers/structure.guarded_projection.md) | Repeated guarded field copies in one local region (three distinct destination fields by default) | All | | [`function_size`](references/checkers/function_size.md) | Function lines, statements, complexity, nesting and parameters; one switch for five diagnostics | All | | [`test.integrity`](references/checkers/test.integrity.md) | Tautological assertions and tests without a meaningful assertion; one switch for two diagnostics | All | | [`test.deletion`](references/checkers/test.deletion.md) | Removed test files, assertion erosion and changed snapshot paths in changed audits; one run-level diagnostic with error and warning forms | All; run-level | | [`flow.handling`](references/checkers/flow.handling.md) | Swallowed exception handlers and long `??` chains whose defaults are all bare literals; one switch for two diagnostics | Python, Java, JavaScript, JSX, TypeScript, TSX | | [`type.contract`](references/checkers/type.contract.md) | Aggregated nullable declarations, bare nullish fallbacks and oversized unions; one switch for two diagnostics | TypeScript, TSX | | [`type.annotation`](references/checkers/type.annotation.md) | Broad or bare Python annotations and invalid forward annotations | Python | | [`type.signature`](references/checkers/type.signature.md) | Missing Python parameter and return annotations | Python | | [`type.broad`](references/checkers/type.broad.md) | Recognized broad type markers and JSON serialization outside proven outputs and permitted library inputs | All; markers differ per language | | [`type.boundary`](references/checkers/type.boundary.md) | Recognized library results and callback inputs used without typed conversion | All | | [`unused.parameter`](references/checkers/unused.parameter.md) | Parameters without resolved read usage | All | | [`unused.function`](references/checkers/unused.function.md) | Non-exported functions and methods without resolved references | All | | [`unused.field`](references/checkers/unused.field.md) | Fields without reads; initialization and writes alone do not count | All | | [`unused.return`](references/checkers/unused.return.md) | Known non-void results discarded at a call site; always a warning | All | | [`type.assertion`](references/checkers/type.assertion.md) | Unchecked casts and assertions | Python, Java, TypeScript, TSX, Rust | | [`type.suppression`](references/checkers/type.suppression.md) | Foreign suppression directives and malformed or unused next-line exceptions | All | | [`imports.wildcard`](references/checkers/imports.wildcard.md) | Python wildcard imports | Python | | [`architecture.owner`](references/checkers/architecture.owner.md) | Missing or overlapping responsibility owners | All | | [`architecture.structure`](references/checkers/architecture.structure.md) | Selected modules outside their configured owning locations | All | | [`architecture.import`](references/checkers/architecture.import.md) | Dependencies forbidden by configured boundaries | All | | [`architecture.dispatch`](references/checkers/architecture.dispatch.md) | Language and rule identity comparison or match/switch dispatch | All | | [`architecture.object_model`](references/checkers/architecture.object_model.md) | Non-underscore module-level functions in configured extension paths; Go reports unexported lowercase package-level functions too, receiver methods, trait methods and Java are not reported | Python, Go, JavaScript, TypeScript, TSX, Rust | Every analyzer registers the same base set of 19 diagnostic IDs: `unused.parameter`, `unused.function`, `unused.field`, `unused.return`, `type.boundary`, `type.suppression`, `size.lines`, `size.statements`, `size.complexity`, `size.nesting`, `size.parameters`, `architecture.owner`, `architecture.structure`, `architecture.import`, `architecture.dispatch`, `architecture.object_model`, `structure.guarded_projection`, `test.tautology` and `test.vacuous`. `test.deletion` is not part of that set: no analyzer registers it, and it is produced by the run-level deletion gate only in `--base` and `--staged` mode. The remaining nine diagnostic IDs are registered per language, and a registered diagnostic can only report for the analyzer that registered it: | Analyzer | Additional diagnostic IDs | |---|---| | Python | `type.annotation`, `type.signature`, `type.assertion`, `type.broad`, `imports.wildcard`, `flow.swallow` | | Go | `type.broad` | | Java | `type.assertion`, `type.broad`, `flow.swallow` | | JavaScript and JSX | `type.broad`, `flow.swallow`, `flow.fallback` | | TypeScript and TSX | `type.assertion`, `type.broad`, `type.nullable`, `type.union`, `flow.swallow`, `flow.fallback` | | Rust | `type.assertion`, `type.broad` | Key differences: - `unused.return` is always a warning, snapshot-only `test.vacuous` findings are warnings, and `test.deletion` reports a changed snapshot path as a warning; every other diagnostic reports errors. Warnings never change the exit code. - One Python annotation can report twice: `typing.Any` triggers both `type.annotation` and `type.broad`. - `architecture.object_model` is registered by every analyzer, but candidate matching checks the leading `_` rather than export status: Go unexported lowercase package-level functions and Rust file top-level `fn` declarations (including `fn main`) are reported, whereas Go receiver methods, Rust inline `mod`/`impl`/`trait` functions and Java files produce no findings. - Language-specific markers (`type.broad`), cast/assertion forms (`type.assertion`), foreign lint attributes (`type.suppression`), test candidates (`test.integrity`) and shared Rust limits are documented on each checker page and in the [checker index](references/checkers.md#shared-rust-analysis-limits). Full detail for every checker — role, language differences, options, defaults, types and correct/incorrect configuration — is on its own page linked from the [checker index](references/checkers.md). ## Checker configuration Each repository commits its policy at `.pluvy/pluvy.json`; the gate never changes it. The policy separates global file selection from checker options: ```json { "version": 2, "include": ["src/*", "tests/*"], "exclude": [], "third_party_modules": [], "checkers": { "function_size": {"lines": 40}, "architecture.owner": { "owners": [{"name": "domain", "paths": ["src/domain/*"]}] } } } ``` Rules that apply to every checker: - `enabled` is a strict boolean, defaulting to `true`. JSON `true` or `false` only: `"false"`, `0` and `null` are errors. Omit `enabled: true` and entries that only repeat defaults. - Unknown checker IDs and unknown options are errors, including when the checker is disabled. The same rejection applies inside nested option objects. - `function_size` is one checker with one switch owning the five `size.*` diagnostics; suppression comments name those diagnostic IDs, not the checker key. - `include` and `exclude` are the only global file selectors and must stay at the top level. - `third_party_modules` is a top-level list of exact import specifiers; in Rust a configured external crate root also covers sub-items imported from that crate while keyword roots (`crate`, `self`, `super`) stay internal. It grants a directional library-input exception for erased dictionaries, not a file or checker exemption. - `type.broad.encoding` holds four lists, all empty by default: `encoders`, `decoders`, `outputs` and `instance_outputs`. They extend built-in serialization recognition; they never exempt broad annotations, casts or incoming library results. ```json { "version": 2, "third_party_modules": ["vendor.client"], "checkers": { "structure.guarded_projection": {"min_fields": 4}, "type.broad": { "encoding": { "encoders": ["vendor.client.encode"], "outputs": [{"call": "vendor.client.publish", "arguments": [0]}] } } } } ``` An invalid policy, rejected before any file is checked: ```json { "version": 2, "checkers": { "function_size": {"enabled": "false"}, "type.broad": {"maximum": 3}, "syntax.invalid": {"enabled": false} } } ``` The string flag fails the strict boolean, `maximum` is not a `type.broad` option, and `syntax.invalid` is not a checker. Malformed configuration fails closed with exit code 2. Thresholds, excludes, owners, boundaries and enable flags are architecture decisions: changing any of them requires a separate full audit and review before the change is committed. `--staged` refuses with exit code 2 while a policy change is staged, but the gate does not record whether the audit ran, so the audit and review are the committer's obligation. Disabling a checker or raising a limit is never remediation. The full option list, defaults, types and examples for each checker are on the page linked from the [checker index](references/checkers.md). ## Pointing other agents at this skill For agents that take their instructions from a repository instruction file (such as AGENTS.md), paste this pointer into that file — manual paste only; never auto-rewrite a user's instruction file: ```markdown When adopting, configuring, or running pluvy, or triaging its findings, first read `.agents/skills/pluvy/SKILL.md` and follow it. ``` ## References - [Agent integration notes](references/agent-integration.md) — integration paths for any agent and the limits that apply. - [Checker index](references/checkers.md) — the 22 checkers and the 29 diagnostic IDs, with coverage tables and one page per checker. - [Approved next-line diagnostic exceptions](references/comment-suppressions.md) — suppression directive syntax, validation rules and snapshot scope. - [Policy sample](references/policy-sample.md) — a compact policy covering file selection, owners, import boundaries and function-size thresholds.