Python Code-pattern Investigator & Nonsense Analyzer - KISS/YAGNI harness for AI-generated code
pip install pcina==0.9.0 Copy PIP instructions
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.
Pure stdlib. Python >= 3.10. Zero runtime dependencies.
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:
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.
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:
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.
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/ 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 (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.
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).
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:
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).
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).
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[...]):
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:
If a discovered file fails to parse, pcina reports it everywhere instead of quietly ignoring it (Ruff's E999 precedent):
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.
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 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.
Driven by the autonomous enhancement loop — see docs/enhancement-loop.md (journal + backlog) and docs/agentic-loop-goal.md (v0.1.1 results).
ai-generated-code ast code-quality dead-code kiss linter static-analysis yagni
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
None of the files in this release were uploaded with provenance metadata.
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.




