Metadata-Version: 2.4
Name: z43-hooks
Version: 0.1.10
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`)

Deterministic include rewriting in three stages: **normalize** (the
include string: disk casing, repo-local includes as quoted-relative paths),
**group** (bucket partition - main header, repo-local, second-party,
third-party, Windows, system - with exact blank-line structure) and
**order** (sort within each bucket). Full behavior:
[docs/cpp-include.md](docs/cpp-include.md).

- Options: `--stage normalize|group|order|all` (default `normalize`; `all`
  runs the three in memory and writes once), `--fix` (the only writer),
  `--dry-run`, `--format text|json`, `--roots DIR` (repeatable extra index
  root), plus the generation modes `--emit-categories` (clang-format
  `IncludeCategories` YAML) and `--guard-order-sensitive` (`// clang-format
  off` guards around ACIS-family stretches).
- Exit: check mode (default) writes nothing - 0 clean (warnings allowed), 1
  would-change, 2 degraded (unreadable file, missing `--roots` dir or
  unlocatable `foreign_roots` entry). `--fix`: 0 all applied, 1
  could-not-apply or leftover, 2 degraded. A missing include root **fails
  closed**: no file is checked or rewritten.
- Config: `[tool.z43.includes]` `tier_order` / `thirdparty_groups` /
  `order_sensitive` / `main_header_pairs` / `bucket_order` replace the
  shipped defaults (`z43_hooks/cpp_include_data.py`) wholesale.
  `foreign_roots` declares another repo's tree in the consuming repo's own
  pyproject, so a shared hook config needs no per-repo `--roots`; `paths`
  are alternatives tried in order (relative to the pyproject, `${VAR}`
  expanded), the first existing one containing `marker` wins:

  ```toml
  [[tool.z43.includes.foreign_roots]]
  name = "SuperMash"
  paths = ["${SUPERMASH_SOURCE_DIR}", "../SuperMash/SuperMash"]
  marker = "XCore/XCore.h"
  ```

- Report categories (`case`, `quoting`, `pch`, `unresolved`, `moves`,
  `reorders`, `layout`, `kept`) are counts, not rule codes: no registry
  entry and no `z43: ignore` suppression.

## 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
```
