Metadata-Version: 2.4
Name: z43-hooks
Version: 0.1.9
Summary: Sim4Life repo-standard C++/Python checks and change gate (pre-commit hooks).
Author-email: ITIS Foundation <devops@itis.swiss>
License-Expression: Apache-2.0
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Topic :: Software Development :: Quality Assurance
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: tree-sitter
Requires-Dist: tree-sitter-cpp
Provides-Extra: gate
Requires-Dist: ruff; extra == "gate"
Requires-Dist: bandit[toml]; extra == "gate"
Dynamic: license-file

![z43-hooks logo](docs/z43_logo.png)

# z43-hooks

Repo-standard C++/Python checks and the change gate used by
`SuperMash/git_hooks/.pre-commit-config.yaml` (hosted repo, pinned by tag).
One checker dispatches by file suffix; one `[tool.z43]` table in a repo's
`pyproject.toml` is the only place rules are activated, tightened, or
excluded; one report/exit-code contract runs through every entry point.

- `z43-checks` - rules ruff cannot express, over any mix of paths. `.py`
  files get the stdlib-AST Python rules (missing `Final`, singleton naming,
  assert/`# nosec` placement, single-use TypeVar, unguarded module-scope work,
  advisory NamedTuple/module-length); C/C++ files
  (`.cpp .cxx .cc .h .hpp .hxx .inl`)
  route to the C++ rule registry: house rules (include guards, redundant
  `virtual`, file-scope `using namespace`, wide-string concat, base-alias
  visibility) and pyd binding-tree rules (throws, binding docstrings,
  `.def` lambdas, `.export_values()`). `--fix` applies the mechanical fixes,
  `--unsafe-fixes` adds the rename tier, `--dry-run` previews the `--fix`
  counts without writing. `--select`/`--ignore` choose codes
  or category stems for one run; `--list-codes` prints the rule map. The
  path-level `path-space` check judges every path it is given, whatever the
  file type - directory arguments see only the checkable suffixes, so the
  pre-commit hook (which passes every staged file individually) is the
  complete sweep. Exit:
  0 clean, 1 findings, 2 the run was degraded (a file could not be seen at
  all) - never a silent zero.
- `z43-change-gate` - runs ruff + bandit + the checks above and reports only
  findings on lines added by the staged diff (advisory `info` findings join
  the report only with `--include-info`). One policy inversion:
  `nosec-redundant` never blocks a commit - dead-`# nosec` cleanup is driven
  by whole-file `z43-checks --fix`, so a per-commit diff gate must not wait
  on it. Path-level codes (`path-space`) bypass the added-line filter: a
  staged path is being committed now, whether or not its content changed.
  Exit: 0 clean, 1 findings on added lines, 2 a tool or the staged
  diff could not run.
- `z43-cpp-include` - the deterministic include normalizer (see below).
  Check-by-default; `--fix` is the only writer.
- `z43-audit` - the deep audit the incremental gate cannot be: whole-tree
  pybind sweeps (docstring layout, Raises: attribution, entity guards, weak
  types) and, under `z43-audit stubs MODULE`, the generated `.pyi` side.
  `--ignore CATEGORY` reports a category but never gates on it; exit:
  0 clean, 1 findings, 2 degraded.

`z43_hooks/autofix.py` remains an importable module (its `main()` still
runs the same fix pipeline); its old standalone console script is gone with
no alias - use `z43-checks --fix`.

`z43_hooks/audit.py` keeps its own category vocabulary (the codes above are
the per-line gate rules; the audit's heuristics - `weak-type`,
`legacy-enum`, `export-values`, `unchecked-entity-deref`,
`missing-raises-section`, `split-docstring-literal`, `bad-none-default`,
`cpp-name-in-docstring`, ... - are whole-tree findings) with severities
`defect` (gates) / `review` / `artifact` / `defer` / `info` (advisory,
`--include-info`). `--ignore <category>` reports the category in full but
never gates on it, so a verification pass can measure a grandfathered family
without failing on it: `export-values` is measured every run and its site
count is printed even when the category is ignored. The same marker dialect
applies: `// z43: ignore[code]` on the flagged line or inside the owning
`.def(...)` downgrades a defect to info (`[suppressed]`).

## Rule map

Every shipped rule is a declaration in the registry `z43_hooks.core.RULES`
(code, level, scope, fix tier). Discover it from the tool: `z43-checks --list-codes --format json`.

| Code                   | Level | Scope    | Fix tier            | Fires on                                                                                                                                                              |
| ---------------------- | ----- | -------- | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `final-missing`        | error | all      | safe                | a module-level binding never rebound and never mutated after the bind, not `Final` (except-handler, `__main__`-guard binds and implicit type aliases exempt)         |
| `final-maybe-missing`  | error | all      | unsafe              | a never-rebound binding whose object is mutated after the bind (attr/subscript store, or a container mutator on a container-literal bind) - `Final` is advisory there, implicit type aliases exempt |
| `naming-module`        | error | all      | unsafe              | an `UPPER_CASE` name bound to a singleton instance                                                                                                                    |
| `nosec-missing`        | error | all      | safe                | an `assert` in non-test code with no `# nosec`                                                                                                                        |
| `nosec-redundant`      | error | all      | safe                | a `# nosec` in a test file (bandit skips tests)                                                                                                                       |
| `typevar-single-use`   | error | all      | report-only         | a `TypeVar` used once in a signature                                                                                                                                  |
| `script-main-guard`    | info  | all      | report-only         | module-scope code that runs at import outside any `if __name__ == "__main__":` guard (a guard excuses only its own block; packages/`setup.py`/tests/`__main__` exempt)|
| `tuple-namedtuple`     | info  | all      | report-only         | a multi-field `tuple[...]` return, advisory                                                                                                                           |
| `module-length`        | info  | all      | report-only         | a module past the soft line limit, advisory                                                                                                                           |
| `suppression-unused`   | error | all      | safe                | a `# z43: ignore` marker that covers nothing                                                                                                                          |
| `path-space`           | error | all      | report-only         | a staged path with a space in the file or folder name (any file type; unwaivable by marker - no line owns a path)                                                     |
| `virtual-redundant`    | error | all      | safe                | a C++ member declared `virtual` with `override`/`final`                                                                                                               |
| `ns-using`             | error | all      | report-only         | a file-scope `using namespace` in a C++ header                                                                                                                        |
| `boost-deprecated`     | error | all      | report-only         | a banned boost API on a line of code (the std:: equivalent is the house shape; comment text and `NOLINT` lines never fire)                                            |
| `tr-wide-split`        | error | all      | safe                | a split `tr()`/`QT_TR_NOOP()` string whose continuation segment carries an encoding prefix                                                                            |
| `guard-missing`        | error | all      | safe                | a C++ header with neither `#pragma once` nor a classic `#ifndef X`/`#define X` guard
                                                                          |
| `guard-mixed`          | error | all      | report-only         | a C++ header carrying both `#pragma once` and a classic guard                                                                                                              |
| `super-alias-visibility` | error | all    | unsafe            | a configured base alias (`[tool.z43.checks.super-alias-visibility] names`; dormant when empty) that is public/protected instead of private, or targets a non-direct base (that second shape is report-only: retargeting changes name lookup) |
| `throw-type`           | error | pyd-only | unsafe              | a bare `std::runtime_error` whose message complains about input (the rewrite to `XCORE_VALIDATE_NOT` changes the Python-visible type)                                 |
| `throw-macro-spelling` | info  | pyd-only | safe                | a correct-type throw spelled raw instead of `XCORE_RAISE_IF`/`XCORE_VALIDATE_NOT`                                                                                     |
| `throw-macro`          | info  | all      | safe                | a call site of an ad-hoc throw macro the shared `<XCore/CommonMacros.h>` replaces                                                                                     |
| `throw-macro-broken`   | error | all      | report-only         | a `#define` throwing `std::runtime_error(os)` with no `os` (instantiation cannot compile), and its call sites                                                         |
| `enum-export-values`   | error | pyd-only | unsafe (diff-gated) | a `.export_values()` call — measured whole-file, gated on added lines                                                                                                 |
| `doc-split`            | error | pyd-only | safe                | a binding docstring split across adjacent string literals                                                                                                             |
| `doc-multiline`        | error | pyd-only | safe                | a `\n`-escaped prose docstring literal (safe only when delimiter-safe)                                                                                                |
| `doc-long`             | info  | pyd-only | report-only         | a binding docstring past 4000 characters, advisory                                                                                                                    |
| `lambda-long`          | info  | pyd-only | report-only         | a `.def` lambda past the `[tool.z43.checks.lambda-long]` line limit, advisory                                                                                         |
| `lambda-passthrough`   | info  | pyd-only | report-only         | a single-call-body `.def` lambda (excepting `py::init` and `cls`-absorbing static-property getters)                                                                   |

Level: `error` fails a run, `info` is advisory and never does (pass
`--include-info` to see it). Scope: `all` checks every file of the language;
a `pyd-only` scope fires only under a `pyd` directory segment. Fix tier:
`safe` runs under `--fix`, `unsafe` needs `--unsafe-fixes`, `report-only`
(None) never rewrites. `diff-gated` codes are reported and counted by
whole-file `z43-checks` without failing it (legacy sites stay visible, they
do not block), while `z43-change-gate` fires them on lines a commit adds.

## Activation model

`[tool.z43.checks]` in the nearest repo `pyproject.toml` that carries a
`[tool.z43]` table (walked up from each target path - nested per-package
pyprojects without a table are stepped over, ruff's rule for `[tool.ruff]`,
so a monorepo's build files never shadow the repo's activation) is the single
source of what is enforced. The pre-commit hook passes no selection args, so
the hook, an editor, a CLI run, and CI never disagree:

```toml
[tool.z43]
# Only build/ and .mypy_cache/ ship built-in; every vendored tree is named
# here (fragments match any single path segment, case-insensitively).
exclude = ["build", ".mypy_cache", "vendor_dir", "gen-py"]
extend-exclude = ["generated"]  # APPENDS instead of replacing (ruff semantics)

[tool.z43.checks]
select = ["final-missing", "throw-type"]  # explicit activation (see below)
ignore = ["naming-module"]     # opt codes/stems out repo-wide
strict = ["B024", "F822"]      # replaces the gate's ruff zero-tolerance set
strict-cpp = ["boost-deprecated", "virtual-redundant"]  # replaces the C++ zero-tolerance set
```

`select` is the activation list: with it, only the listed codes/stems run;
without it, every registered rule stays active. A new built-in rule does not
go live in a configured repo until the repo adds it, exactly like
`[tool.ruff.lint] select`. `ignore` still overrides select (ruff's order).

CLI `--select`/`--ignore` override the table for one run only. Matching is
at hyphen boundaries: `--ignore nosec` covers `nosec-missing` and
`nosec-redundant`; `--select final` covers `final-missing` and
`final-maybe-missing`, a bare `fin` matches nothing. Exclusions are forced
everywhere, the fix pipeline
included: neither `z43-checks --fix` nor the autofix module writes into an
excluded tree (a stderr note, not a silent skip), and an explicitly passed
vendored path is still skipped from checks. Any directory below the config
root that ships its own `.clang-format` auto-skips as vendored.

## The include normalizer (`z43-cpp-include`)

Three stages share one tool: **normalize** (fix the include *string*:
case-correctness against headers on disk, main-header quoting, repo-local
includes converging on the quoted-relative form), **group** (bucket
partition, blank-line structure)
and **order** (sort WITHIN buckets). `--stage` accepts `normalize`
(default), `group`, `order` and `all`; `all` runs normalize THEN group
THEN order in memory and writes the combined result once (for
already-normalized modules - the safe rollout path stays one stage per
commit). Normalize is line-local and never relocates an include; group
relocates lines but never rewrites a string; order permutes includes in
place within each bucket's written lines (structure untouched).

- **check mode is the default** and writes nothing: exit 1 on any
  would-change (a string rewrite for normalize, a line that moves or a
  blank-line-only layout rebuild for group), exit 0 with visible warnings
  otherwise, exit 2 for a degraded
  run (unreadable file, bad `--roots`). `--fix` is the only writer and
  exits by leftovers (0 all applied, 1 could-not-apply or leftover, 2
  degraded). `--dry-run` prints per-category/per-module counts;
  `--format json` renders per-file changes `{line, category, from, to}`
  and moves `{line, from_bucket, to_bucket}` plus the counts.
- **case**: an include matching an on-disk header only case-insensitively
  is rewritten to the disk casing (Linux builds break on the wrong case),
  for angle and quoted forms and module-qualified paths alike. Duplicated
  interior slashes in an otherwise resolvable relative path collapse the
  same way (`"../Mod//Foo.h"` -> `"../Mod/Foo.h"`).
- **quoting**: repo-local includes converge on the quoted-relative form.
  The TU's own header (`Foo.cpp` -> `Foo.h` in the file's dir, or -
  absent there - in an ancestor's mirrored `include/` tree:
  `mod/impl/Foo.cpp` -> `mod/include/impl/Foo.h`; the `*_pyd.h` module header
  in `pyd` dirs; and the header paired through `[tool.z43.includes]`
  `main_header_pairs` - default `test_{name}`, so `test_Foo.cpp` claims
  `Foo.h`, looked up from the file's dir up to the repo root, nearest
  wins, silently absent when the header does not exist) must be a quoted
  local include, and any include whose target is a file inside the
  edited file's repo (the config root: the dir whose pyproject governs
  the file) is rewritten to the quoted path relative to the file
  (`"../Foo.h"`, same-dir `"Foo.h"`): an angle-written `<Mod/Foo.h>` or
  root-quoted `"Mod/Foo.h"` resolving under the file's own root, or one
  resolving under any root inside the repo; or a spelling NO index root
  resolves that some ancestor directory of the file carries on disk -
  walking up to the config root, nearest ancestor first, which is how
  container-relative module spellings (`<XCore/Foo.h>` written relative
  to a SuperMash-style module container) resolve without any root
  configuration, robust to running from anywhere. At each ancestor the
  spelling is also sought under its `include/` subdirectory: a module
  exposing public headers through `-I <module>/include` (QTech-style)
  carries its sources' bare `<q_gl.h>` spellings there, and they converge
  on the quoted relative path like any other repo-local target (a
  vendored copy under such an `include/` tree is an excluded tree, so it
  is never claimed). A name already known
  as system, third-party (`thirdparty_groups`), or order-sensitive
  (ACIS-family) is never claimed by such a carry, and neither is a copy
  inside an excluded vendored tree. An include resolving under a root
  outside the repo keeps the angle form (a quoted cross-repo include
  becomes angle); nothing is guessed.
- **unresolved**: an include resolving nowhere and not a known system /
  third-party / order-sensitive (ACIS-family) spelling is warned with a
  per-module count, never rewritten - and warnings alone never fail a
  run. A path an ancestor directory carries (per the quoting rules)
  counts as resolved.
- **group buckets**, in emitted order: (0) the TU's pinned main header,
  (1) repo-local - an on-disk target inside the edited file's repo (the
  config root): an own-root resolution, a root inside the repo, a
  spelling an ancestor directory carries, or a relative `"../Foo.h"`
  that stays inside it, (2) second-party - resolution under a root
  outside the repo (a `--roots` root) or a relative walk that leaves it
  (the repo split derives from the file's path, never from config), (3)
  third-party - a configured
  `thirdparty_groups` prefix or order-sensitive (ACIS) spelling, (4)
  Windows SDK headers - `windows.h` and friends, including names like
  `WinError.h` and `Wtsapi32.h` whose macros collide with in-repo
  headers; a quoted spelling that resolves to a file inside the repo is
  still repo-local because resolution precedes the family check, and
  the family membership then also blocks an ancestor walk from
  hijacking the angle form, and (5) system/STL. **An
  include that resolves nowhere lands in bucket 3**: the conservative
  bucket, because an unresolvable target looks like a library header. No
  line is ever dropped. The emission SEQUENCE is per-repo config:
  `[tool.z43.includes] bucket_order` (a full permutation of the six
  bucket names, e.g. system first; anything else keeps the default);
  classification never changes, and a position-0 PCH pin always leads.
- **blank-line structure is exact**: one blank line between every pair of
  blocks - between buckets, and WITHIN the repo-local, second-party and
  third-party buckets, where each block is one unique folder (repo-local:
  the same-dir block, then the own-module-tree blocks, then one block per
  distinct foreign target folder in tier/folder order; second-party: one
  per target folder; third-party:
  one per configured `thirdparty_groups` library, one for the ACIS
  family, one for the unresolved tail) - none inside a block; the blocks
  are laid out in the order stage's rank order, so a following order pass
  confirms the layout instead of reshuffling it. Trailing `//` comments
  ride with their include; everything outside an include region is
  untouched. A region whose rebuild differs only in blank lines (no
  include changes line) is reported as a `layout` would-change.
- **hard boundaries** the tool never crosses: `extern "C"` blocks,
  pragmas, comment lines, and real code. Regions are rebuilt only BETWEEN
  boundaries: a section comment stays put and the includes under it regroup.
- **`// clang-format off` regions are pinned too**: every include line
  inside an off/on marker pair is held exactly as written against ALL
  stages - never rewritten, regrouped or reordered - and the region acts
  as a hard boundary, so no outside include can flow into it. This is the
  escape hatch for order-sensitive runs (SDK headers that must precede a
  wrapper which `#undef`s their macros, generators whose headers extend
  a library's): guard them with `// clang-format off` and both formatters
  leave them alone.
- **conditional inclusion is a pinned unit, not a hard boundary**: runs separated
  only by `#if`/`#ifdef`/`#else`/`#elif`/`#endif` directives share ONE
  region - the unguarded includes sort freely across them - while each
  guard block (directives, blanks and guarded includes) is emitted
  verbatim as a unit anchored directly after its written-predecessor
  unguarded include (at the region head when it has none); each
  `#if`/`#else`/`#elif` arm still regroups inside itself, and a blank
  adjacent to a guard block stays exactly as written. A guarded block
  therefore rides along with the include it was written behind instead of
  stranding its neighbors in separate regions. The exception: a guard
  block whose body holds anything but includes and directives (real
  code, a comment, a pragma, an `extern` block - as in
  `#ifdef WIN32` / `#include <windows.h>` / a helper function /
  `#endif`) is itself a hard boundary: runs on either side regroup
  independently, so no sorted include can ever be pushed below the code
  inside the guard.
- **pch**: a precompiled-header include at position 0 of the include
  block (any spelling whose basename is a known PCH, including a
  relative `"../PreCompiled.h"`) is canonical bucket-0 content: never a
  would-change, never relocated, never judged - the delete-vs-keep
  decision is a human audit. A PCH-named include anywhere ELSE is an
  ordinary include: bucketed like any header, NOT moved to position 0.
- Group operates on canonical strings (run normalize first, or
  `--stage all`); run standalone on mis-cased includes it still groups
  correctly - classification is case-folded - and the would-change list
  just carries the moves.
- **order sorts WITHIN each bucket** (after grouping; it never moves an
  include across a bucket or a hard boundary, and the position-0 PCH pin
  stays put). Repo-local and second-party includes are ranked by COARSE
  naming-convention **tiers** from `[tool.z43.includes] tier_order` (an
  ordered glob list like `*ui`, `xcoremath`, `xcore*`), one block per
  unique target folder within a tier (folder names alphabetical); a NEW
  module matching an existing tier glob lands in that tier
  automatically, and an unmatched module sorts after every named tier
  (never dropped). Module names are repo knowledge, so the shipped
  `tier_order` is EMPTY: a repo without the key ranks every foreign
  module in one untiered block, folder order. The SuperMash layout, for
  example:

  ```toml
  [tool.z43.includes]
  tier_order = ["*headless*", "*ui", "*application", "*simulator*",
                "*postpro*", "*kit", "*toolkit", "xcoremodeling",
                "xcoremath", "xcore*"]
  ```

  A module-infrastructure directory inside a module
  (`testsuite`, `tests`, `pyd`, `ext`, `gpc`, `yocto`) is credited to
  the module that owns it, so `XCore/testsuite` headers travel with the
  XCore tier rather than dropping into the untiered tail.
  Within the repo-local bucket the includes whose target lives in
  the including file's OWN directory OPEN the bucket as a leading block
  before every other block (house style: same-folder `"Foo.h"` neighbors
  first). Next come the file's own module **tree**: every target under
  the top-level module directory the file itself hangs under (a file in
  `QTech/impl/vk` counts the whole `QTech/` subtree - parent walks,
  `include`, `impl`, `testsuite` - as own; the source directory a repo
  nests its modules in is a packaging level, not a tree) ranks before
  every FOREIGN tier, closest folder first; tiers then order the foreign
  includes, adjacent modules first. Second-party includes are never own.
  The **Windows** bucket (SDK
  headers: `windows.h`, `WinSock2.h`, `windowsx.h`, `shlwapi.h`, …) sits
  between third-party and the C++ standard library: `WinSock2.h`, then
  `windows.h`, then the dependents alphabetically. The **third-party** bucket is sorted in configured per-library
  (`thirdparty_groups` order: boost, Eigen, VTK, pybind, ...) alphabetical
  within, unmatched third-party after the configured
  groups; the **system** bucket is alphabetical. Every sort is
  case-insensitive with the written position as a stable tiebreak, so
  output is deterministic across platforms.
- **order-sensitive carve-out**: an include matching an
  `[tool.z43.includes] order_sensitive` pattern (the ACIS api/error
  family: `<api.err>`, `*.hxx`, `Windows.h`) is FIXED in its written
  line - excluded from any sort, so its relative order with the rest of
  the family survives normalize+group+order unchanged (the macro-ordering
  contract). Adding a pattern to `order_sensitive` in a repo's table
  protects a new family the same way. The ACIS undefinition header
  (`UndefACIS.h`) is pinned **last** within the third-party bucket (it
  redefines the error macros, so it must follow every header consuming
  them).
- Index roots = the nearest `pyproject.toml` dir plus `--roots` repeats,
  always resolved absolute (a relative target or `--roots` must still
  rank modules and tiers correctly); the shared exclude/auto-skip layer
  applies and excluded trees are never even indexed (a vendored path
  passed explicitly stays skipped, exit unchanged).
- **`--emit-categories`** is a generation mode, not a stage: it prints
  the clang-format `IncludeCategories` YAML block built from the tier
  list, the third-party families, the Windows family and the module
  directories discovered
  under `--roots` (the first root is this repo, later roots are other
  repos folding into third-party - clang-format buckets are
  spelling-based and the table knows no second-party category), then
  exits without reading files; a bad `--roots` still prints the table
  with exit 2. Regenerate after adding a module. clang-format applies the
  FIRST matching regex, so the third-party and Windows entries precede
  the repo catch-all. The house `.clang-format` keeps `SortIncludes:
  false` - z43-hooks is the sorter - so the table is for a repo opting
  into clang-format sorting; there it pairs with
  `MainIncludeChar: Quote` / `IncludeIsMainRegex: '(Test)?$'`, and
  order-sensitive (ACIS/Windows) runs need `// clang-format off` guards
  - clang-format cannot pin a category in place. The table only
  approximates `--stage order`: clang-format categories are spelling
  regexes, so the own-module-tree lead, the same-dir block and the
  one-block-per-folder split cannot be expressed.
- **`--guard-order-sensitive`** writes exactly those guards: every
  maximal order-sensitive (ACIS-family) include stretch not already
  inside a `// clang-format off` region gets an off/on marker pair, so
  a sorting clang-format leaves those lines exactly as written. Check
  mode (default) exits 1 on unprotected stretches and writes nothing;
  `--fix` is idempotent - the pairs it wrote read back as guards.

The report categories (`case`, `quoting`, `pch`, `unresolved`, `moves`,
`reorders`, `layout`, `kept`) are REPORT CATEGORIES with counts - not rule codes:
no registry entry, no per-line `z43: ignore` suppression, and the code
table above is unchanged. `[tool.z43.includes]` (`tier_order` /
`thirdparty_groups` / `order_sensitive` / `main_header_pairs` /
`bucket_order`) replaces the shipped defaults
wholesale; the defaults live in `z43_hooks/cpp_include_data.py`, measured
off the real trees. A shaped-but-invalid `bucket_order` (not a full
permutation of the six bucket names) or a `main_header_pairs` entry
without `{name}` warns on stderr and falls back to its default; an
unshaped value falls back silently. Output is idempotent (`stage(stage(x)) == stage(x)`
for each stage and
for `all`) and clang-format idempotent under the consumer `.clang-format`
files (include
sorting stays off there - the two tools never fight).

## Fix safety

Like ruff, fixes are tiered (the tiers live in the same rule registry):

| Tier                      | Codes                                                                                                                                                                                  | Contract                                                                                                                                                                                      |
| ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| safe (`--fix`)            | `final-missing`, `nosec-missing`, `nosec-redundant`, `suppression-unused`, `virtual-redundant`, `tr-wide-split`, `guard-missing`, `throw-macro-spelling`, `throw-macro`, `doc-split`, `doc-multiline` | only adds/removes what the checker prescribes; semantics cannot change                                                                                                                        |
| unsafe (`--unsafe-fixes`) | `naming-module`, `final-maybe-missing`, `throw-type`, `enum-export-values`, `super-alias-visibility`                                                                                    | renames the singleton and same-file usages / annotates `Final` on a binding whose object is mutated / changes the Python-visible exception type / deletes public enum names / moves a base alias to a private section - review the diff |
| report-only               | `typevar-single-use`, `script-main-guard`, `tuple-namedtuple`, `module-length`, `path-space`, `ns-using`, `boost-deprecated`, `guard-mixed`, `throw-macro-broken`, `doc-long`, `lambda-long`, `lambda-passthrough` | needs judgement                                                                                                                                                                               |

Every Python edit must keep the file `compile()`-able, and every C++ edit
must re-parse with no new grammar error nodes, or it is skipped and counted.
After fixing, the fix pipeline best-effort sorts imports via
`ruff check --fix --select I` when ruff is on PATH.

The C++ front end (tree-sitter, a hard dependency) counts grammar error nodes
per run and surfaces them in the report footer only - macro-heavy headers
never flood the report or fail a run.

The gate's tool invocations live in `z43_hooks/tools.py` (one seam for
ruff/bandit/git, unpinned - bump by rebuilding the hook env). A pip-installing
consumer pulls the same unpinned ruff/bandit pair with the `gate` extra
(`z43-hooks[gate]`); the `z43-change-gate` hook lists them as
`additional_dependencies` instead, since pre-commit cannot request extras.
When a tool cannot run, the gate says so on stderr and exits 2 instead of
passing the commit on silence.

## Suppressing a finding

mypy-style, on the offending line (comment position only - prose about the
syntax is not a marker):

```python
MAX = 3  # z43: ignore[final-missing]   one code
X = f()  # z43: ignore[final-missing, naming-module]
Y = g()  # z43: ignore                  every z43 code on this line
```

C++ uses the same dialect in `//` comments (scanned inside comment spans
only, so a marker inside a string or raw-string body is never a marker):

```cpp
virtual Foo() override;  // z43: ignore[virtual-redundant]
```

For the binding-tree (pyd) codes, a marker anywhere inside the owning
`.def(...)` call covers every finding in that call - one ignore comment
tames a whole lambda body instead of one line:

```cpp
m.def("go", [](int n) {
    // z43: ignore[throw-type]
    if (n < 0) throw std::runtime_error("n must be >= 0");
    return n;
}, "Go.");
```

A marker whose listed code covers nothing is reported as
`suppression-unused` (ruff's RUF100 analogue) - and `--fix` prunes it, so
stale ignores cannot accumulate.

Path-level codes are the dialect's limit made explicit: a finding with no
source line (`path-space`) can carry no marker, so the footer offers no
waiver hint for it. `ignore` in `[tool.z43.checks]` (or `--ignore`) opts it
out - the config layer, not a line comment.

`path-space` is adapted from [check-spaces-in-paths](https://github.com/dyollb/check-spaces-in-paths)
(MIT, Bryn Lloyd) - rewritten for this rule registry, not copied.

Develop:

```bash
python -m pip install pre-commit && pre-commit install
pre-commit run --all-files   # or: python -m pytest -q, ruff check .
```

`.pre-commit-config.yaml` is this repo's own standard ruff-based config.

Release: bump `version` in `pyproject.toml`, then tag `vX.Y.Z` matching it
and push the tag. The CI (`.gitlab-ci.yml`) runs the tests and publishes the
wheel to this project's PyPI package registry. Bump the `rev:` in the
consumer config afterwards.

Install a published version (replace `<PROJECT_ID>` with this project's
numeric id, shown on the project overview page). Add `[gate]` to also pull
the change gate's ruff/bandit:

```bash
pip install "z43-hooks[gate]" \
  --index-url https://git.speag.com/api/v4/projects/<PROJECT_ID>/packages/pypi/simple
```
