Metadata-Version: 2.5
Name: pcina
Version: 0.8.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

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.

## 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. 8.37 (stretched rating)
print(scores["raw_overall"])   # e.g. 9.25 (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` 1, `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. `scores.raw_overall`
(additive `pcina/1` field) keeps the pre-transform number for audits. Scores
are advisory; only `pcina check` budgets gate.


## Quickstart

```bash
pcina scan src/                 # advisory report
pcina check src/                # budget gate: exit 1 on violations (CI)
pcina report --md src/          # markdown report (drops into an agent context)
pcina baseline --save src/      # snapshot findings
pcina baseline --compare src/  # delta vs snapshot
pcina scan --json src/          # stable pcina/1 JSON schema
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 |
| 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 | complexity | `pipeline-sprawl` |
| `>= 3` functions writing one module-level mutable that others read | 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.

## Terminal output (real run)

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

```
== pcina scan: src/  (25 files, 1530 LLOC) ==

complexity : 9.9/10   paranoia : 10.0/10
nesting    : 9.6/10   hardcode : 9.8/10
deadcode   : 9.7/10   yagni    : 9.8/10
clever     : 9.7/10   size     : 10.0/10

src/pcina/files.py:25 [warn][complexity] cognitive complexity 18 in discover - reader must track nested state
  fix: split the function or name complex conditions as predicates
src/pcina/metrics/dataflow.py:65 [info][nesting] nesting depth 3 - one level from trouble
  fix: consider inverting the outer condition

statistics:
  loc=2408 lloc=1530 files=25 functions=199 classes=13
  docstring_coverage=84% comment_ratio=4%
  avg_cc=3.6 max_cc=10 p75_cc=5.0
  raises=12 try_except=11 bare_excepts=0
  dead_candidates=21 yagni_candidates=4 magic_values=1

Your code has been rated at 9.09/10
```

Finding lines are single-line, greppable: `file:line [sev][aspect] message`.

## 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 9.35, zero errors; slop 3.84 — `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 | 4 re-validation raises in an internal helper + two broad `except Exception: return (0, 0)` swallows | clean 9.35, zero errors; slop 3.84 — `warn paranoia: 4 raise-guards in internal helper - validation belongs to trust boundary`, two `warn paranoia: broad/bare except - may swallow real bugs (confirm the handler re-raises or narrows)` |
| `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 9.35, zero errors; slop 7.23 — `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`, repeated `30`, `0.5`) where the clean twin names `BAR_WIDTH` / `FULL_CELL` / `EMPTY_CELL` | clean 9.35, zero errors; slop 8.60 — `warn hardcode: 5 magic values - name them as module constants (0.95, 0.95, 30, 0.5, 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).

## 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 `--fail-on`, when given) |
| 1 | budget violation (`pcina check`), including a file pcina could not parse; or a finding at/above the `check --fail-on` severity |
| 2 | error / CLI usage problem (e.g. no Python files found at all, malformed `# pcina: no-check` comment) |

Scores themselves are advisory; `pcina check` fails only on explicit budget
violations — plus, optionally, the severity gate below — never on the rating.
Exit codes are a stable contract (same 0/1/2 convention as Ruff/ESLint).

## Advanced controls

**`check --fail-on error|warn`** — additionally exit 1 when a finding at or
above the chosen severity exists (pylint's `--fail-on` convention: the flag
names a minimum severity that must fail the gate). Absent the flag, `check`
behavior is unchanged: only budgets gate. Invalid severities are usage errors
(exit 2).

**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).

## License

MIT
