Metadata-Version: 2.5
Name: pcina
Version: 0.13.0
Summary: Python Code-pattern Investigator & Nonsense Analyzer - KISS/YAGNI harness for AI-generated code
Project-URL: Homepage, https://github.com/AlexKay28/pcina
Project-URL: Repository, https://github.com/AlexKay28/pcina
Project-URL: Issues, https://github.com/AlexKay28/pcina/issues
Project-URL: Changelog, https://github.com/AlexKay28/pcina/blob/main/docs/agentic-loop-goal.md
Author: alexkay28
License: MIT
License-File: LICENSE
Keywords: ai-generated-code,ast,code-quality,dead-code,kiss,linter,static-analysis,yagni
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Quality Assurance
Classifier: Topic :: Software Development :: Testing
Requires-Python: >=3.10
Description-Content-Type: text/markdown

# pcina

[![CI](https://github.com/AlexKay28/pcina/actions/workflows/regression-wall.yml/badge.svg)](https://github.com/AlexKay28/pcina/actions/workflows/regression-wall.yml)
[![PyPI](https://img.shields.io/pypi/v/pcina.svg)](https://pypi.org/project/pcina/)
[![Python](https://img.shields.io/pypi/pyversions/pcina.svg)](https://pypi.org/project/pcina/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)

**pcina** = **P**ython **C**ode-pattern **I**nvestigator & **N**onsense
**A**nalyzer — a tool that investigates the *patterns* in your Python code
(the named shapes of over-engineering) rather than style trivia, and prices
the nonsense those patterns add for the next reader.

Automatic checker for **KISS/YAGNI paradigm alignment**. pcina parses your Python code
(pure `ast`, one pass) and rates it per aspect out of 10 — mechanizing the ethos of the
classic KISS/YAGNI advice ("write the minimum code a new reader understands in one
pass; build nothing speculative") into a single fast command. It targets the
over-defensive, over-abstracted, over-nested output that both AI agents and humans
produce — without importing anyone's opinion on formatting or typing.

## What it looks like

A compact "enterprise waterfall" (validation steps as single-use private
functions plus an uncalled one-method orchestrator class — the fixture
ships at `examples/signup_waterfall.py` so this output is reproducible):

```
$ pcina scan examples/signup_waterfall.py

complexity : 10.00/10   paranoia : 10.00/10
nesting    : 10.00/10   hardcode : 10.00/10
deadcode   :  9.35/10   yagni    :  8.95/10
clever     : 10.00/10   size     : 10.00/10

examples/signup_waterfall.py:32 [info][deadcode] no callers found for 'SignupValidationService' - deletion candidate (...)
  fix: delete the definition if no dynamic dispatch references it
examples/signup_waterfall.py:32 [info][yagni] single-method class 'SignupValidationService' - prefer a function
  fix: replace the class with a plain function (add state only when real)

Your code has been rated at 8.60/10
verdict: CLEAN
```

`pcina check` exits non-zero on must-fix findings (error/warn by default) — made
for CI and for AI-agent self-repair loops. Real terminal output; both misses and
catches are journaled openly in [docs/benchmark.md](docs/benchmark.md).

**New: [Why simple code — the full motivation, survey and benchmark
narrative](docs/why-simple-code.md)** — why AI made code verbosity an
economic problem, how pcina's pair benchmark measures a code-quality
checker honestly, the catalog of verbosity patterns it detects, and how
the score doubles as a training-signal for AI coding pipelines.

**System map: [docs/architecture.md](docs/architecture.md)** — the live
as-is architecture with component, pipeline, gate and evidence-system
diagrams, the full project structure, and the table of frozen contracts.
**Benchmark: [docs/benchmark.md](docs/benchmark.md)** — the evaluation
corpus, its pre-registered anti-leakage protocol, and the results it
licenses (headline: dev 1.000 · frozen holdout 0.941 · hard-100 0.966
pair accuracy).

**AI agents: [SKILL.md](SKILL.md)** — drop-in operating instructions for
coding agents (the scan → must-fix → re-check loop, parse contracts, and
the fix-don't-suppress etiquette).

**Also new: [`docs/theory/`](docs/theory/)** — a 14-file arXiv-survey-style
theory corpus (one section per file, cross-linked), grounding the whole
argument in the literature: Goodhart's law and proxy failure modes,
LLM-as-judge bias studies, LLM code-quality measurement, reward hacking
in RL training loops — plus the pair methodology, the pattern taxonomy,
the adversarial generalization results, and honest limitations.

## Install

Pure stdlib. Python >= 3.10. Zero runtime dependencies.

```bash
pip install pcina        # from PyPI
# or
pipx install pcina       # isolated CLI tool
# or straight from GitHub
pip install git+https://github.com/AlexKay28/pcina.git
```

Use it from Python too — scores and findings are plain data:

```python
from pcina.analyzer import analyze
from pcina.metrics import findings_for
from pcina.scoring import score

project = analyze(["src/"], [])
findings = findings_for(project)
scores = score(project, findings)
print(scores["overall"])        # e.g. 7.35 (stretched rating)
print(scores["raw_overall"])   # e.g. 8.50 (pre-transform linear audit trail)
for f in findings:
    if f.severity in ("warn", "error"):
        print(f.severity, f.aspect, f"{f.file}:{f.line}", f.message)
```

### Scoring

Every finding carries a severity weight (`error` 3, `warn` 2, `info` 1) times
an aspect multiplier (a public data table in `pcina/finding.py`). The rating
is pylint-shaped `10 - 10*P/LLOC` passed through a **monotone stretch
transform** (`10 - 10*min(1, P/LLOC)**0.7`), so mild findings visibly move the
score instead of piling up in a 9.4–10 corridor. Aspect scores publish at
two decimals and the overall is **derived from the published aspects**
(inverting the transform per aspect and recomposing — ADR-002 §10): identical
reported aspect dicts necessarily imply an identical reported overall, so the
evidence trail always explains the verdict at its own precision.
`scores.raw_overall` (additive `pcina/1` field) keeps the pre-transform number
for audits. Scores are advisory; only `pcina check` budgets gate.

## Adopt it

In any repo's [pre-commit](https://pre-commit.com) config — findings are
project-wide (cross-file deadcode, shared-mutable-web), so the hook runs
serially:

```yaml
repos:
  - repo: https://github.com/AlexKay28/pcina
    rev: v0.13.0  # pin a tag
    hooks:
      - id: pcina
```

Or as a one-line GitHub Action (the job fails only when pcina reports
must-fix error/warn findings — `pcina check` controls that):

```yaml
- uses: AlexKay28/pcina@v0.13.0  # pin a tag, not main
  with:
    paths: src/
```


## Quickstart

```bash
pcina scan src/                 # advisory report + verdict line
pcina check src/                # CI gate: exit 1 on budget violations OR error/warn findings
pcina check --fail-on none src/ # budgets only (the pre-v0.9.3 semantics)
pcina report src/               # markdown report (add -o FILE to write it)
pcina baseline --save src/      # snapshot findings
pcina baseline --compare src/   # delta vs snapshot
pcina scan --json src/          # stable pcina/1 JSON schema (incl. the verdict key)
pcina scan --diff main src/     # only findings on lines changed vs BASE (git)
pcina scan --exclude 'tests/*' src/
```

## The 8 aspects

| Aspect | Principle | Meaning |
|---|---|---|
| complexity | KISS | a reader should understand a function in one pass |
| paranoia | KISS | validate at trust boundaries, not inside internal helpers |
| nesting | KISS | flat beats nested — guard clauses, early return |
| hardcode | KISS | no magic values forcing the reader to reconstruct facts |

**v0.9.0 (formula-constants amendment, behavior note):** the price of a
magic value follows the value-and-consumption shape, never the textual
placement. A literal that occurs exactly once in its function and is
consumed by its own statement's expression (`j - i >= 3`, `ord(lo) - 96`,
`m in (4, 6, 9, 11)`, `29 if leap else 28`) is an inline formula constant —
not a finding. Repeated values and bare call-argument/subscription
payloads keep their findings. The placement-symmetric price: a
SCREAMING_SNAKE module assignment of a bare scalar magic literal with
exactly ONE use site (`MINIMUM_RUN = 3`) emits `single-use-constant` —
hoisting a one-use value out of the finding path does not name it into a
shared domain fact; 3+ in one module aggregate to a warn. Constants with
2+ uses, data tables, tuples, strings and default-argument config surface
stay good practice. ADR-002 section 12 has the normative clauses.
| clever | KISS | if a reader must mentally execute the line, rewrite it |
| deadcode | YAGNI | unused code was never (or no longer) needed |
| yagni | YAGNI | no speculative abstraction for hypothetical futures |
| size | KISS | one outcome per function; a docstring is the 30-second test |

### Dataflow-clarity findings (ADR-003, scan-only)

Inter-function dataflow, AST + intra-file call graph only, all severity `info`,
no budget, no `check` gate — Ruff/Pylint `too-many-*` rules are per-function
counts and never see these shapes, so the whole category stays advisory:

| Finding | Aspect | Message marker (stable, greppable) |
|---|---|---|
| `>= 5` linear single-use function steps passing one unlabeled dict/list, **or one orchestrator calling `>= 5` single-use steps sequentially over the same shared dict/list** | complexity | `pipeline-sprawl` |
| `>= 3` functions writing one module-level mutable that others read, **`del obj[key]` counts as a write** | deadcode | `shared-mutable-web` |
| encode (`json.dumps`/`marshal`/`repr`) re-parsed in a direct callee/caller | paranoia | `serialize-in-file` |

Frozen thresholds live in `pcina.finding.DATAFLOW_THRESHOLDS` beside
`SEV_WEIGHT`/`ASPECT_MULT`; changing them requires a wave-3 corpus
(ADR-003 anti-leakage rule). Fires-on/silent-on fixture pairs are pinned in
`tests/test_dataflow.py`.

**v0.7.1 (wave-3 re-freeze, behavior note):** chains crossing hops by keyword
argument, single-use `@staticmethod` steps reached through their class, and
in-place mutator-method calls on a shared dict (`x.update(...)` and friends)
now count as sprawl writes/round-trip channels; encode-to-decode pairs also
match keywords. `*args` misalignment and non-static method chains stay
out (documented conservative seams); all numeric thresholds are unchanged.

**v0.9.0 (wave-4 wording amendment, behavior note):** the sibling-orchestrator
topology now fires `pipeline-sprawl` — one function body sequentially calling
`>= 5` distinct single-use module-level steps over the same shared dict/list
(each step mutating it, through iteration aliases like
`for row in record["rows"]` included, and returning None) is the hidden
pipeline; the LINEAR telephone-chain form is unchanged. `del obj[key]` on a
module-level mutable now counts as a write toward `shared-mutable-web`
(`del name` still neither reads nor rebinds). All thresholds, markers, and
severity unchanged; scan-only.

## Terminal output (real run)

`pcina scan src/` on pcina's own source (v0.13.0):

```
== pcina scan: src  (34 files, 2749 LLOC) ==

complexity : 10.00/10   paranoia : 10.00/10
nesting    : 9.84/10   hardcode : 9.86/10
deadcode   : 10.00/10   yagni    : 9.18/10
clever     : 10.00/10   size     : 10.00/10

src/pcina/analyzer.py:837 [info][hardcode] hardcoded URL 'ftp://' - extract to module constant
  fix: move the URL to a named module constant
  ...

== findings summary: 71 info, 0 warn, 0 error - 2.58 findings/100 LLOC
  complexity: 0 info, 0 warn, 0 error
  nesting: 4 info, 0 warn, 0 error
  ...
must fix: none

statistics:
  loc=4861 lloc=2749 files=34 functions=355 classes=14
  docstring_coverage=90% comment_ratio=6%
  avg_cc=3.9 max_cc=10 p75_cc=5.0

Your code has been rated at 9.08/10
verdict: CLEAN
```

Finding lines are single-line, greppable: `file:line [sev][aspect] message`.
The **verdict line** (v0.9.3) is the one-line decision agents can't skim
past: `verdict: CLEAN` iff the run has zero error and zero warn findings,
`verdict: FIX REQUIRED (N error, M warn)` otherwise — info findings never
block. When blocking findings exist, a `must fix (N):` list repeats them
worst-first (severity, then file:line), above the statistics. The same
verdict rides in the JSON as the additive top-level `verdict` key
(status, must_fix_count, per-severity counts, per-aspect counts,
findings-per-100-LLOC). See [docs/architecture.md](docs/architecture.md)
for the full system map and [docs/migration-0.9.x.md](docs/migration-0.9.x.md)
for the released behavior deltas.

## Examples

`examples/` holds 4 side-by-side (SBS) pairs: same job, same public API, one KISS
clean twin and one realistic-slop twin. All numbers below are **measured** with
`PYTHONPATH=src python -m pcina.cli scan --json <file>` (single-file scan; the
`no-caller` deadcode info on every example function is the documented single-file
false positive — see "Known false positives"). The regression pins live in
`tests/test_examples.py`: the published scores are pinned (two decimals)
and every backtick-quoted finding text in this table must match a
message from a fresh scan, so both numbers and quotes fail CI on drift.

| Pair (clean / slop) | Job | Anti-pattern in the slop | What pcina reports |
|---|---|---|---|
| `nested_loops_clean.py` / `nested_loops_slop.py` | count cells above a threshold in a grid | arrow-shaped `if`/`for` nesting up to depth 7 instead of guard clauses / comprehension | clean 10.00, zero errors; slop 1.76 — `warn nesting: nesting depth 6` in `warm_cells` and `warn nesting: nesting depth 7` in `warm_rows`, plus `complexity` spillover |
| `paranoid_guard_clean.py` / `paranoid_guard_slop.py` | parse a `WIDTHxHEIGHT` string | two broad `except Exception: return (0, 0)` swallows around tangled `is not None` ceremony (the raise-guards sit at the module's entry and are boundary-legal since v0.9.0/#17 — the swallows are the paranoia) | clean 10.00, zero errors; slop 3.17 — two `warn paranoia: broad/bare except - may swallow real bugs (confirm the handler re-raises or narrows)`, plus `nesting` spillover |
| `yagni_engine_clean.py` / `yagni_engine_slop.py` | total an invoice (net + tax) | speculative `TaxStrategy` single-method class + 5-key strategy registry, order tuple and fallback no caller ever selects | clean 10.00, zero errors; slop 6.32 — `info yagni: single-method class 'TaxStrategy'` (+ `warn paranoia` spillover) |
| `magic_chart_clean.py` / `magic_chart_slop.py` | render an ASCII progress bar | inline magic values (`0.95` twice, repeated `30`) where the clean twin names `BAR_WIDTH` / `FULL_CELL` / `EMPTY_CELL` | clean 10.00, zero errors; slop 8.29 — `warn hardcode: 4 magic values - name them as module constants (0.95, 0.95, 30, 30)` |

Mechanical gate: `python3 scripts/backlog_gate6.py` re-measures all 8 files from
the repo checkout and exits 0 only if every clean twin keeps `overall >= 9.0`
with zero error findings, every slop stays strictly below its clean twin, and
each slop still triggers its designated hard-mode aspect (nesting, paranoia,
yagni, hardcode respectively).

## Benchmark — the evidence behind the scores

Every accuracy claim pcina makes is backed by a **frozen, pre-registered,
adversarial pair benchmark**: 300 task-twin pairs (same task, minimal vs
verbose implementation, 10.6× mean expansion, median 7 vs 83 lines) plus a
**hard-100 adversarial set** built specifically to defeat the frozen
heuristics. Full documentation: **[docs/benchmark.md](docs/benchmark.md)** —
corpus construction, anti-leakage protocol, per-construct results, and
exact reproduction commands (pure stdlib, offline).

**Headline results** (pair accuracy: KISS side must score *strictly* higher;
ties count against):

| Evaluation | n | Accuracy | Note |
|---|---:|---:|---|
| Dev split (tuning set) | 121 | **1.000** (121/121, Wilson CI [0.969, 1.000]) | current build, 2026-11-09 |
| Hard-100 adversarial set | 89 | **0.966** (86/89) | 0.247 at the wave-era one-shot → 0.966 today via ADR-governed amendments |
| **Holdout** (ids 151–300) | 102 | **0.941** (Wilson CI [0.878, 0.973]) | read **exactly once**, ever — a frozen pre-registered record, not a re-measurable claim |

**Why you can trust it:** the split was declared *before* generation,
the holdout was read one-shot and journaled verbatim, rejected pairs are
kept in the CSV (nothing was deleted to improve a number), every miss became
a *diagnosed construct class* or a *documented residual* — never an ad-hoc
score bump — and the holdout's 0.941 *above* the tuning set's original 0.826
is itself evidence that no overfitting occurred. The analyzer is also
forced through its own gate: `pcina check src` exits 0 and self-scans
**9.08/10, verdict CLEAN** (the §24 dogfood clause). Reproduce:
`python3 scripts/pair_metrics.py --split dev`, `python3
scripts/hard_metrics.py`, or all gates at once with
`python3 scripts/regression_wall.py` (this is what CI runs on every push).

**Paper / artifact usage.** The corpus (`benchmark/`), protocol
(`benchmark/PROTOCOL.md`), decision records (`docs/decisions/`, `docs/adr/`),
and reproduction scripts (`scripts/`) are packaged as a self-contained,
offline evaluation artifact — designed to be referenced as-is by an arXiv
paper and mirrored on Papers with Code (no external services, pinned
predictor `scores.overall`, frozen metric definition "KISS strictly
higher, ties count against"). See [docs/benchmark.md](docs/benchmark.md)
§5 for the exact reproduce commands and §6 for the file map.

## Known false positives (honest)

**Dynamic dispatch.** The deadcode aspect flags "no callers found" for functions wired
up dynamically — CLI entry points, plugin registries, `__all__` re-exports. Static
analysis cannot see those callers. **Verify before deleting anything** pcina marks
as a deletion candidate.

pcina already excludes from deadcode analysis: dunders (`__init__`, `__call__`, …),
contents of `__init__.py` (import surface), functions named `main`, and test files.
Typing imports used only in annotations, class bases and cross-module re-exports
count as uses — all verified on real-world repos (see `docs/field-triage.md`).

**Intentional import markers.** Two conventions from the wider tooling
ecosystem (Ruff/Vulture) that pcina honors:

```python
from pkg import thing as thing  # redundant alias = explicit re-export marker
import encodings.idna           # noqa: F401  # noqa = intentional, do not report
```

**Dataflow findings are scope-insensitive (Vulture convention).** The three
dataflow-clarity findings match call targets by *name only* (a dotted call
`x.step(d)` resolves to a file function `step`; a `@staticmethod` in a class
joins the module call graph). Real code can trip that: a 5+ hop chain of
single-use wrappers passing a plain value (not a dict) still reads as a
"chain", and an injected-object protocol (`svc.validate(x)`) whose method
names collide with single-use file functions can light a chain up. All three
findings stay `info`, scan-only and advisory for exactly this reason; the
honest-miss direction exists too (same-named definitions collapse to one
entry, mutator-method lists are finite).


## Exit codes (contract)

| Code | Meaning |
|---|---|
| 0 | clean — no budget violations and no finding at/above the `check --fail-on` severity (default: no error/warn findings) |
| 1 | gated: a budget violation (`pcina check`), including a file pcina could not parse; or a finding at/above the `check --fail-on` severity (default `warn` since v0.9.3) |
| 2 | error / CLI usage problem (e.g. no Python files found at all, malformed `# pcina: no-check` comment) |

Scores themselves are advisory; `pcina check` gates on explicit budget
violations and, by default since v0.9.3, on error/warn findings — never on
the rating. Exit codes are a stable contract (same 0/1/2 convention as
Ruff/ESLint).

## Advanced controls

**`check --fail-on none|error|warn|info`** — the severity gate, **default
`warn`** since v0.9.3 (ADR-002 §24): an error or warn finding fails the gate
even with no budget violation. The flag names the minimum severity that
must fail (pylint's `--fail-on` convention): `error` gates errors only;
`info` is the strictest; `none` restores the pre-v0.9.3 budgets-only
semantics. Invalid severities are usage errors (exit 2). Migration notes:
[docs/migration-0.9.x.md](docs/migration-0.9.x.md).

**Inline suppression, line-scoped only** — Ruff's line-level suppression
convention (`noqa` / `ruff: ignore[...]`):

```python
def f(x):
    try:
        return x
    except:  # pcina: no-check              # all aspects, THIS line only
        return None
    except:  # pcina: no-check [paranoia]   # one aspect, comma list ok
        return None
```

Held by the whole pipeline — `scan`, `check`, `report`, `baseline` and the
budget gate always agree: a suppressed broad except no longer trips the
`bare_except` budget either. Deliberate limits, to prevent over-muting:

- suppresses **that physical line only** — never a block, file or aspect globally;
  there is no config `ignore` list and no file-level directive;
- the marker must be a real comment — the same text inside a string does nothing;
- malformed comments (`[nosuchaspect]`, trailing prose) are exit-2 usage errors,
  never silent no-ops.


## Unparseable files (never silently skipped)

If a discovered file fails to parse, pcina reports it everywhere instead of
quietly ignoring it (Ruff's E999 precedent):

- every report names it — `== unparsed files (NOT analyzed) ==` in the terminal
  and markdown, `scope.skipped` (`file`/`line`/`reason`) in the JSON
- `pcina check` fails with a `parse-error` violation per skipped file — a file
  no gate can see must fail the gate
- while any file is unparsed, cross-file deadcode verdicts (`no-caller`,
  project-wide `unused-import`) are suppressed rather than guessed from
  incomplete references
- `scope.files` counts analyzed files only; discovered = `files + len(skipped)`

## Known behavior: encoding (non-UTF-8 bytes are named, never silently mangled)

Each file is strict-decoded first. When bytes outside UTF-8 appear in a place
that still parses — typically string literals or comments — the file is
**analyzed after U+FFFD replacement but never silently**: every surface names
it (`scope.corruptions`, a list of `{file, replacements}`, in the JSON;
`== encoding corruption` block in term and markdown). Corruption records are
analysis-integrity visibility only: they are not findings, do not affect
scores, and never change exit codes. Bytes that break parsing (e.g. U+FFFD
identifiers) go through the unparsed-files path above. Valid multi-byte UTF-8
(emoji, CJK) is never flagged.

## Known behavior: broad except that provably re-raises is a passthrough (v0.8.0)

A broad `except Exception:` handler whose body contains a **bare `raise`**
(a re-raise of the in-flight exception, anywhere in the handler — the
retry/passthrough idioms) is **not flagged** as `broad-except`: the finding's
own advice ("confirm the handler re-raises or narrows") is already satisfied.
This is the Ruff BLE001 re-raise exemption; `raise <expr>` inside the handler
raises a *new* exception and does **not** silence the finding. Plain swallows
(assign-and-return, log-only) fire exactly as before, `# pcina: no-check` is
unaffected, and the `bare_excepts` statistic/budget still count every broad
handler, re-raising or not.

## Roadmap

Driven by the autonomous enhancement loop — see
[docs/enhancement-loop.md](docs/enhancement-loop.md) (journal + backlog) and
[docs/agentic-loop-goal.md](docs/agentic-loop-goal.md) (v0.1.1 results).

Open tracker items: [#24](https://github.com/AlexKay28/pcina/issues/24)
— agent-facing reporting (v0.9.3 delivered the verdict/must-fix/exit-policy
slice; remaining: the warn-bites-score amendment, protocol-governed) and
[#25](https://github.com/AlexKay28/pcina/issues/25) — the residual
pattern-family map (value-enum class zoos, decorator-erased call graphs,
qualified-arm ladders, capsule/formula residuals).

## License

MIT
