Skip to main content

Code quality metrics based on Golden Ratio (φ) mathematical invariants

Project description

phi-complexity

Code quality metrics based on Golden Ratio (φ) mathematical invariants

PyPI version Python 3.9+ License: MIT Tests

phi-complexity is the first code quality library that measures the health of your Python code using universal mathematical invariants derived from the Golden Ratio (φ = 1.618...).

Unlike pylint (cultural rules) or radon (McCabe metrics), phi-complexity answers:

"Is this code in resonance with the natural laws of order, or is it collapsing under its own entropy?"


⚡ Quick Start

pip install phi-complexity
# Audit a file
phi check my_script.py

# Audit a folder
phi check ./src/

# Start the Sovereign Web IDE (Local-First browser interface)
phi ui

# Generate a Markdown report
phi report my_script.py --output report.md

# CI/CD strict mode (exit 1 if radiance < 75)
phi check ./src/ --min-radiance 75

Python API

from phi_complexity import auditer, rapport_console, rapport_markdown

# Get metrics as a dict
metrics = auditer("my_script.py")
print(metrics["radiance"])          # → 82.4
print(metrics["statut_gnostique"])  # → "EN ÉVEIL ◈"
print(metrics["oudjat"])            # → {"nom": "process_data", "ligne": 42, ...}

# Print console report
print(rapport_console("my_script.py"))

# Save Markdown report
rapport_markdown("my_script.py", sortie="report.md")

📊 Metrics

Metric Description Mathematical basis
Radiance Score Global quality score (0–100) 100 - f(Lilith) - g(H) - h(Anomalies) - i(Fib)
Variance de Lilith Structural instability Population variance of function complexities
Shannon Entropy Information density H = -Σ p·log₂(p)
φ-Ratio Dominant function ratio max_complexity / mean → should tend toward φ
Fibonacci Distance Natural size alignment
Zeta-Score Global resonance ζ_meta(functions, φ) converging series

Gnostic Status Levels

Score Status Meaning
≥ 85 HERMÉTIQUE ✦ Stable, harmonious, production-ready
60–84 EN ÉVEIL ◈ Potential exists, some entropy zones
< 60 DORMANT ░ Deep restructuring recommended

🧭 Command Stability Matrix

Command Stability Purpose Output / Side-effects
phi check Stable Audit radiance for files/folders Console (Aesthetic v0.1.0) or JSON
phi ui Stable Launch Local-First Web IDE Starts Uvicorn server + opens browser
phi report Stable Markdown report Writes report.md if --output
phi oracle Stable Release gate (radiance + tests) Console; exits 1 on failure
phi harvest Experimental AST vectors collection Writes .phi/harvest.jsonl
phi metadata Experimental Metadata summary & purge (harvest/vault) Summaries; sanitized JSONL
phi vault / phi graph / phi canvas Experimental Vault storage + graph export + Obsidian canvas Writes under .phi/ (JSON, DOT/ASCII, .canvas)
phi search Experimental Query the vault Console/JSON; reads .phi/vault.jsonl
phi seal / phi heal Experimental Seal + auto-suture via LLM May call local LLM (--url); writes seal metadata in .phi/
phi spiral Experimental Radiance spiral visualization Console ASCII only

Tip: keep phi check/phi report/phi oracle in CI. Use experimental commands locally first and pin outputs under .phi/ in .gitignore if not needed in VCS.


🔍 Sample Output

╔══════════════════════════════════════════════════╗
║      PHI-COMPLEXITY — AUDIT DE RADIANCE          ║
╚══════════════════════════════════════════════════╝

  📄 Fichier : my_script.py
  📅 Date    : 2026-04-08 17:11

  ☼  RADIANCE     : ██████████████░░░░░░  72.6 / 100
  ⚖  LILITH       : 11221.9  (Structural variance)
  🌊 ENTROPIE     : 2.48 bits  (Shannon)
  ◈  PHI-RATIO    : 3.43  (ideal: φ = 1.618, Δ=1.81)
  ζ  ZETA-SCORE   : 0.3656  (Global resonance)

  STATUT : EN ÉVEIL ◈

  🔎 OUDJAT : 'process_data' (Line 42, Complexity: 376)

  ⚠  SUTURES IDENTIFIED (2):
  🟡 Line 18 [LILITH] : Nested loop (depth 2). Consider a helper function.
     >> for j in range(b):
  🔵 Line 67 [SOUVERAINETE] : 'load_data' receives 6 arguments. Encapsulate in an object.
     >> def load_data(path, sep, enc, cols, dtype, na):

🚀 Phidélia Cyber Station (Web IDE)

phi-complexity dispose maintenant (via les dépendances [web]) d'un véritable IDE Web Local Souverain (phi ui), fonctionnant intégralement en local avec communication WebSockets :

  • Glassmorphism & Néon : Design premium ultra-soigné et sans dépendances JS externes (Vanilla JS/CSS).
  • Monaco Editor : Le moteur haute-performance derrière VS Code, intégré hors ligne.
  • WebSocket Streaming : Dialogue asynchrone direct entre l'orchestrateur Python et le frontend.

🚀 CI Innovation Suite (Open Source)

phi-complexity embarque maintenant une suite orientée productivité/dev/ops :

  • AI AutoFix Studio : règles de mutation déterministes pour appliquer rapidement des corrections CI.
  • Flow Intelligence : classification dédiée des annulations liées à la concurrence (WORKFLOW_CONCURRENCY_CANCELLED).
  • Runner Sentinel : détection explicite des blocages de queue runner (RUNNER_QUEUE_STALL).
  • Ops & Engineering Control Plane : snapshot exportable JSON/Markdown (succès/échecs/cancelled, MTTR, causes racines, tendances).
  • Dev Productivity Environment : .devcontainer + Makefile + commande make ci-local pour reproduire le pipeline localement.
make setup
make ci-local

🧮 Mathematical Foundations

The Radiance Formula is derived from:

  • φ-Meta Framework (Tomy Verreault, 2026) — Axioms AX-A0 through AX-A58
  • Law of Antifragility (EQ-AFR-BMAD): φ_{t+1} = P_φ(φ_t + k·Var(E_t)·E_t)
  • Cybernetics (Korchounov, Mir, 1975) — Feedback and variance as control metrics
  • Shannon Information Theory — Code as an information channel

The Sovereign Coding Rules are derived from:

  • The C Book (Banahan, Brady, Doran) — Scope hermeticity, resource lifecycle
  • JaCaMo / Multi-Agent Programming — Agent independence and encapsulation

Full mathematical proof: docs/MATHEMATIQUES.md


🏗 Sovereign Architecture

Zero external dependencies.
Pure Python standard library (ast, math, json).
phi_complexity/
├── core.py        ← Golden constants (PHI, TAXE_SUTURE, ETA_GOLDEN...)
├── analyseur.py   ← AST fractal dissection
├── metriques.py   ← Radiance Index calculation
├── rapport.py     ← Console / Markdown / JSON rendering
└── cli.py         ← phi check / phi report

🔗 Integration

Pre-commit Hook

repos:
  - repo: https://github.com/spockoo/phi-complexity
    rev: v0.1.0
    hooks:
      - id: phi-check
        args: [--min-radiance, "70"]

GitHub Action

- name: Phi-Complexity Audit
  run: |
    pip install phi-complexity
    phi check ./src/ --min-radiance 75

Secrets (ADMIN_TOKEN)

  • Never commit ADMIN_TOKEN in tracked files.
  • Store it in environment variables or GitHub Actions Secrets.
  • Use .env.example as a template only:
ADMIN_TOKEN=

📜 License

MIT — Tomy Verreault, 2026

Anchored in the Bibliothèque Céleste — Morphic Phi Framework (φ-Meta)

📜 Historique des Versions (Changelog)

  • v0.2.3 (FastAPI & Phidélia Station) — Actuelle :

    • Lancement de l'IDE Web souverain : Nouveau point d'entrée phi ui qui déploie un orchestrateur local avec frontend premium (Monaco Editor, WebSockets, Vanilla JS).
    • Restauration minutieuse de l'esthétique absolue de la v0.1.0 pour les rapports phi check dans la console.
  • v0.2.2 (Souveraineté & Cybersécurité) :

    • Implémentation du "Cerveau de Sécurité" : Moteur de triage mathématique départageant les failles critiques cybernétiques (CWE-79, CWE-89) des simples anomalies architecturales (Variance Lilith, Complexité).
    • Algorithmes de Mémoire Fail-Fast pour phi_check optimisant à 100% le temps processeur et la RAM lors des audits anti-mots-interdits.
    • Conformité CI parfaite garantissant aucune friction entre Windows et Linux (via normalisation PEP8 stricte).
  • v0.2.1 : Intégration souveraine du phi_check pré-commit natif et de la politique Quality Gate pour GitHub Actions. Réparation des métriques de base.

  • v0.2.0 : Introduction de pydantic pour la vérification de la robustesse, ajouts de structures initiales pour les métriques Souverainete.

  • v0.1.0 : Version primaire. Formule mathématique de base implémentée (Lilith, Shannon, Fib, Radiance).


🔒 Sécurité : Activation du contrôle phi-check

Ce projet utilise un contrôle automatique (pré-commit) qui bloque tout ajout de code contenant certains mots ou outils réservés (par exemple des scripts ou outils reconnus de piratage).

Pour installer et activer le contrôle localement :

pip install pre-commit
pre-commit install

Le contrôle phi-check se lance alors automatiquement à chaque commit.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

phi_complexity-0.2.3.tar.gz (220.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

phi_complexity-0.2.3-py3-none-any.whl (157.1 kB view details)

Uploaded Python 3

File details

Details for the file phi_complexity-0.2.3.tar.gz.

File metadata

  • Download URL: phi_complexity-0.2.3.tar.gz
  • Upload date:
  • Size: 220.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.0rc1

File hashes

Hashes for phi_complexity-0.2.3.tar.gz
Algorithm Hash digest
SHA256 317f9d85a28ad9f97c457e1834eee05292e152577eb9f71e9cadefc9bd159e37
MD5 52adff7c029d3a9610fca13601ab2df4
BLAKE2b-256 cb6264fbb3e05d1297628998fd1eab52bd1987e70b89cc322ec5555509d10be3

See more details on using hashes here.

File details

Details for the file phi_complexity-0.2.3-py3-none-any.whl.

File metadata

  • Download URL: phi_complexity-0.2.3-py3-none-any.whl
  • Upload date:
  • Size: 157.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.0rc1

File hashes

Hashes for phi_complexity-0.2.3-py3-none-any.whl
Algorithm Hash digest
SHA256 04c6c66326abb3bd74ea39b0780339cb472345a1cc871ff9a831e261ab4ce71b
MD5 9dcf18a5561fab03b84c3ff831a7507e
BLAKE2b-256 e7e7bc1cdfbda77177410c889d77edd0f93c2b06fff747704396dc72cf47e9f2

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page