diff --git a/.nojekyll b/.nojekyll deleted file mode 100644 index e69de29bb..000000000 diff --git a/404.html b/404.html deleted file mode 100644 index 8c8965e82..000000000 --- a/404.html +++ /dev/null @@ -1,3194 +0,0 @@ - - - -
- - - - - - - - - - - - - - - - - - - -Quick operational reference for the Resonant Fractal Nature Theory (TNFR). This document provides API-focused definitions for code use only.
---📐 SINGLE SOURCE OF TRUTH FOR MATHEMATICS:
-Mathematical Foundations of TNFR¶
-All mathematical formalization lives there: rigorous definitions, derivations, axioms, proofs, spectral theory, operator algebra, Hilbert spaces, and theoretical foundations.
-This glossary contains only operational quick reference for developers implementing TNFR networks.
-
Code: G.nodes[n]['EPI'], ALIAS_EPI
-Symbol: (\text{EPI}) or (E)
-What: Coherent structural form of a node
-Space: (B_{\text{EPI}}) (Banach space)
-Rules: Modified only via structural operators, never directly
-API: tnfr.structural operators
-Math: §2.2 Banach Space B_EPI
Code: G.nodes[n]['vf'], ALIAS_VF
-Symbol: (\nu_f)
-Units: Hz_str (structural hertz)
-Range: (\mathbb{R}^+) (positive reals; node collapse when (\nu_f \to 0))
-What: Rate of structural reorganization
-API: adapt_vf_by_coherence(), operators
-Math: §3.2 Frequency Operator Ĵ
Code: G.nodes[n]['dnfr'], ALIAS_DNFR
-Symbol: (\Delta\text{NFR})
-What: Structural evolution gradient (drives reorganization)
-Sign: Positive = expansion, Negative = contraction
-Compute: Via default_compute_delta_nfr hook, automatic in step()
-Math: §3.3 Reorganization Operator
Code: G.nodes[n]['theta'], collect_theta_attr()
-Symbol: (\theta) or (\phi)
-Range: ([0, 2\pi)) or ([-\pi, \pi)) radians
-What: Network synchrony parameter (relative timing)
-Phase difference: (\Delta\theta = \theta_i - \theta_j)
-API: Phase adaptation in dynamics
-Math: §4 Nodal Equation
Code: compute_coherence(G) → float ∈ [0,1]
-Symbol: (C(t))
-Formula: (C(t) = \text{Tr}(\hat{C}\rho)) where (\hat{C}) is the coherence operator
-Range: ([0, 1]) where 1 = perfect coherence, 0 = total fragmentation
-What: Global network stability measure
-Math: §3.1 Coherence Operator Ĉ
Code: coherence_matrix(G) → (nodes, W)
-Symbol: (\hat{C})
-Matrix element: (w_{ij} \approx \langle i | \hat{C} | j \rangle)
-Properties: Hermitian ((\hat{C}^\dagger = \hat{C})), positive semi-definite
-What: Operator measuring structural stability between nodes
-Math: §3.1 Theory + §3.1.1 Implementation
Code: G.nodes[n]['Si'], ALIAS_SI, compute_Si_node()
-Symbol: (\text{Si}) (global) or (S_i) (node i)
-Formula: (\text{Si} = \alpha \cdot \nu_{f,\text{norm}} + \beta \cdot (1 - \text{disp}\theta) + \gamma \cdot (1 - |\Delta\text{NFR}|))}
-Range: ([0, 1^+]) typically, higher = more stable reorganization
-What: Capacity for stable structural reorganization
-Weights: (\alpha + \beta + \gamma = 1) (default: 0.4, 0.3, 0.3)
-Math: Mathematical Foundations - Metrics
Code: compute_structural_potential(G, alpha=2.0) → Dict[NodeId, float]
-Symbol: (\Phi_s(i))
-Formula: (\Phi_s(i) = \sum_{j \neq i} \frac{\Delta\text{NFR}_j}{d(i,j)^\alpha}) where (\alpha = 2)
-What: Emergent potential field from network ΔNFR distribution
-Status: ✅ CANONICAL (promoted 2025-11-11)
-Validation: 2,400+ experiments, corr(Δ Φ_s, ΔC) = -0.822, CV = 0.1%
-Physics: Passive equilibrium landscape (minima = potential wells)
-Grammar: U6 STRUCTURAL POTENTIAL CONFINEMENT (Δ Φ_s < 2.0)
-API: tnfr.physics.fields.compute_structural_potential()
-Validation: tnfr.operators.grammar.validate_structural_potential_confinement()
-Math/Physics:
-- UNIFIED_GRAMMAR_RULES.md § U6 - Complete derivation
-- TNFR_FORCES_EMERGENCE.md § 14-15 - Empirical validation
-- src/tnfr/physics/fields.py - Implementation
Interpretation: -- Φ_s minima = passive equilibrium states -- Δ Φ_s < 2.0 = system confined (safe regime) -- Δ Φ_s ≥ 2.0 = escape threshold (fragmentation risk) -- Valid sequences: Δ Φ_s ≈ 0.6 (30% of threshold) -- Violations: Δ Φ_s ≈ 3.9 (195% of threshold)
-Mechanism: Grammar U1-U5 acts as passive confinement (NOT active attractor). Reduces escape drift by 85%.
-The fundamental equation of TNFR governs structural evolution:
-[ -\frac{\partial \text{EPI}}{\partial t} = \nu_f \cdot \Delta\text{NFR}(t) -]
-Where: -- (\frac{\partial \text{EPI}}{\partial t}): Rate of change of structure -- (\nu_f): Structural frequency (reorganization rate) in Hz_str -- (\Delta\text{NFR}(t)): Reorganization gradient (driving pressure)
-Interpretation: -- Structure changes only when both (\nu_f > 0) (capacity) and (\Delta\text{NFR} \neq 0) (pressure) exist -- Rate of change is proportional to both frequency and gradient -- When (\nu_f \to 0), evolution freezes (node collapse) -- When (\Delta\text{NFR} = 0), structure reaches equilibrium
-Implementation: See src/tnfr/dynamics/ for numerical integration
-Theory: §4 The Nodal Equation
The 13 canonical operators are the only way to modify nodes in TNFR. They're not arbitrary functions—they're resonant transformations with rigorous physics.
-For complete specifications with physics derivations, contracts, and usage examples, see AGENTS.md § The 13 Canonical Operators.
-| Symbol | -Name | -Physics | -Grammar Sets | -When to Use | -
|---|---|---|---|---|
| AL | -Emission | -Creates EPI from vacuum via resonant emission | -Generator (U1a) | -Starting new patterns, initializing from EPI=0 | -
| EN | -Reception | -Captures and integrates incoming resonance | -- | -Information gathering, listening phase | -
| IL | -Coherence | -Stabilizes form through negative feedback | -Stabilizer (U2) | -After changes, consolidation | -
| OZ | -Dissonance | -Introduces controlled instability | -Destabilizer (U2), Bifurcation trigger (U4a), Closure (U1b) | -Breaking local optima, exploration | -
| UM | -Coupling | -Creates structural links via phase synchronization | -Requires phase verification (U3) | -Network formation, connecting nodes | -
| RA | -Resonance | -Amplifies and propagates patterns coherently | -Requires phase verification (U3) | -Pattern reinforcement, spreading coherence | -
| SHA | -Silence | -Freezes evolution temporarily (νf → 0) | -Closure (U1b) | -Observation windows, pause for synchronization | -
| VAL | -Expansion | -Increases structural complexity (dim ↑) | -Destabilizer (U2) | -Adding degrees of freedom | -
| NUL | -Contraction | -Reduces structural complexity (dim ↓) | -- | -Simplification, dimensionality reduction | -
| THOL | -Self-organization | -Spontaneous autopoietic pattern formation | -Stabilizer (U2), Handler (U4a), Transformer (U4b) | -Emergent organization, fractal structuring | -
| ZHIR | -Mutation | -Phase transformation at threshold | -Bifurcation trigger (U4a), Transformer (U4b) | -Qualitative state changes | -
| NAV | -Transition | -Regime shift, activates latent EPI | -Generator (U1a), Closure (U1b) | -Switching between attractor states | -
| REMESH | -Recursivity | -Echoes structure across scales | -Generator (U1a), Closure (U1b) | -Multi-scale operations, memory | -
Operators combine into sequences that implement complex behaviors:
-Critical: All sequences must satisfy unified grammar (U1-U6).
-API:
-- tnfr.structural.<OperatorName>() - Individual operators
-- run_sequence(G, node, ops) - Execute operator sequences
-- validate_sequence(ops) - Check grammar compliance
Grammar: See UNIFIED_GRAMMAR_RULES.md for complete rules
-Detailed Specs: See AGENTS.md § The 13 Canonical Operators
-Math: Mathematical Foundations §5
From AGENTS.md:
-| Symbol | -Mathematical | -Code Attribute | -Units | -Range | -Type | -
|---|---|---|---|---|---|
| (\text{EPI}) | -Primary Information Structure | -'EPI' |
-dimensionless | -(B_{\text{EPI}}) | -Coherent form | -
| (\nu_f) | -Structural frequency | -'vf' |
-Hz_str | -(\mathbb{R}^+) | -Reorganization rate | -
| (\Delta\text{NFR}) | -Reorganization operator | -'dnfr' |
-dimensionless | -(\mathbb{R}) | -Evolution gradient | -
| (\theta), (\phi) | -Phase angle | -'theta' |
-radians | -([0, 2\pi)) | -Network synchrony | -
| (C(t)) | -Total coherence | -compute_coherence() |
-dimensionless | -([0, 1]) | -Global stability | -
| (\text{Si}) | -Sense Index | -'Si' |
-dimensionless | -([0, 1^+]) | -Reorganization stability | -
# Access node attributes
-epi = G.nodes[node_id]['EPI']
-vf = G.nodes[node_id]['vf']
-theta = G.nodes[node_id]['theta']
-
-# Compute metrics
-C_t = compute_coherence(G)
-nodes, W = coherence_matrix(G)
-Si = compute_Si_node(G, node_id)
-
-# Apply operators
-from tnfr.structural import Emission, Coherence, Resonance
-run_sequence(G, node_id, [Emission(), Coherence(), Resonance()])
-
-# Evolution step
-from tnfr.dynamics import step
-step(G, use_Si=True, apply_glyphs=True)
-Expose in telemetry:
-- C(t) - Total coherence
-- νf per node - Structural frequency
-- phase per node - Synchrony state
-- Si per node/network - Sense index
-- ΔNFR per node - Reorganization gradient
-- Operator history - Applied transformations
-- Events - Birth, bifurcation, collapse
API: tnfr.utils.callback_manager, history tracking in G.graph['_hist']
TNFR is trans-scale and trans-domain: -- Works from quantum to social systems -- No built-in assumptions about specific domains -- Structural operators apply universally
-Guideline: Avoid domain-specific hard-coding in core engine
-All simulations must be: -1. Seeded: Explicit RNG seeds -2. Traceable: Log operators, parameters, states -3. Deterministic: Same seed → same trajectory
-Tools: RNG scaffolding, structural history, telemetry caches
-The consolidated TNFR grammar system (U1-U6) that replaces the old C1-C3 and RC1-RC4 systems.
-Source of Truth: UNIFIED_GRAMMAR_RULES.md
-Quick Reference: AGENTS.md § Unified Grammar (U1-U6)
-Implementation: src/tnfr/operators/grammar.py
Six Canonical Constraints:
-| Rule | -Name | -Physics Basis | -Requirement | -Canonicity | -
|---|---|---|---|---|
| U1 | -STRUCTURAL INITIATION & CLOSURE | -∂EPI/∂t undefined at EPI=0 | -Start with generator {AL, NAV, REMESH}, End with closure {SHA, NAV, REMESH, OZ} | -ABSOLUTE | -
| U2 | -CONVERGENCE & BOUNDEDNESS | -∫νf·ΔNFR dt must converge | -If destabilizer {OZ, ZHIR, VAL}, then include stabilizer {IL, THOL} | -ABSOLUTE | -
| U3 | -RESONANT COUPLING | -Phase compatibility required for resonance | -If coupling {UM, RA}, verify |φᵢ - φⱼ| ≤ Δφ_max | -ABSOLUTE | -
| U4 | -BIFURCATION DYNAMICS | -∂²EPI/∂t² > τ requires control | -Triggers {OZ, ZHIR} need handlers {THOL, IL}; Transformers need context | -STRONG | -
| U5 | -MULTI-SCALE COHERENCE | -Hierarchical coupling + chain rule | -Nested EPIs require stabilizers {IL, THOL} at each level | -ABSOLUTE | -
| U6 | -STRUCTURAL POTENTIAL CONFINEMENT | -Emergent Φ_s field: Φ_s(i) = Σ ΔNFR_j/d(i,j)² | -Monitor Δ Φ_s < 2.0 (telemetry-based safety) | -STRONG | -
Canonicity Levels: -- ABSOLUTE: Mathematical necessity (direct consequence of nodal equation) -- STRONG: Strong empirical/theoretical support (2,400+ experiments for U6)
-Recent Updates: -- U5 added 2025-11-10 (hierarchical REMESH stabilization) -- U6 promoted to canonical 2025-11-11 (Φ_s field validation complete) - - Replaces experimental "Temporal Ordering" research proposal - - Validated across 5 topologies: ring, scale_free, small-world, tree, grid - - Correlation: corr(Δ Φ_s, ΔC) = -0.822 (R² ≈ 0.68)
-See Also: -- UNIFIED_GRAMMAR_RULES.md - Complete derivations from physics -- AGENTS.md § Unified Grammar - Quick reference -- docs/grammar/U6_STRUCTURAL_POTENTIAL_CONFINEMENT.md - U6 complete specification -- TNFR_FORCES_EMERGENCE.md § 14-15 - U6 validation details -- src/tnfr/physics/fields.py - Φ_s implementation
-Operator that can create EPI from null/dormant states.
-Set: GENERATORS = {emission, transition, recursivity}
-Physics: Only these operators can initialize when EPI=0
-Grammar Rule: U1a (STRUCTURAL INITIATION)
-See: UNIFIED_GRAMMAR_RULES.md § U1a
-Operator that leaves system in coherent attractor state.
-Set: CLOSURES = {silence, transition, recursivity, dissonance}
-Physics: Terminal states preserving coherence
-Grammar Rule: U1b (STRUCTURAL CLOSURE)
-See: UNIFIED_GRAMMAR_RULES.md § U1b
-Operator that provides negative feedback for convergence.
-Set: STABILIZERS = {coherence, self_organization}
-Physics: Ensures ∫νf·ΔNFR dt converges (bounded evolution)
-Grammar Rule: U2 (CONVERGENCE & BOUNDEDNESS)
-See: UNIFIED_GRAMMAR_RULES.md § U2
-Operator that increases |ΔNFR| through positive feedback.
-Set: DESTABILIZERS = {dissonance, mutation, expansion}
-Physics: Without stabilizers, leads to divergence
-Grammar Rule: U2 (CONVERGENCE & BOUNDEDNESS)
-See: UNIFIED_GRAMMAR_RULES.md § U2
-Operators that require phase verification for valid coupling.
-Set: COUPLING_RESONANCE = {coupling, resonance}
-Physics: Resonance requires |φᵢ - φⱼ| ≤ Δφ_max
-Grammar Rule: U3 (RESONANT COUPLING)
-See: UNIFIED_GRAMMAR_RULES.md § U3
-Operators that may trigger phase transitions.
-Set: BIFURCATION_TRIGGERS = {dissonance, mutation}
-Physics: Can cause ∂²EPI/∂t² > τ (bifurcation)
-Grammar Rule: U4a (requires handlers)
-See: UNIFIED_GRAMMAR_RULES.md § U4a
-Operators that manage structural reorganization during bifurcations.
-Set: BIFURCATION_HANDLERS = {self_organization, coherence}
-Physics: Provide stability during phase transitions
-Grammar Rule: U4a (BIFURCATION DYNAMICS)
-See: UNIFIED_GRAMMAR_RULES.md § U4a
-Operators that perform graduated destabilization for phase transitions.
-Set: TRANSFORMERS = {mutation, self_organization}
-Physics: Require recent destabilizer for threshold energy
-Grammar Rule: U4b (requires context + prior IL for ZHIR)
-See: UNIFIED_GRAMMAR_RULES.md § U4b
-This glossary is bidirectionally linked with: -- AGENTS.md references this glossary for term definitions -- UNIFIED_GRAMMAR_RULES.md references this glossary for quick lookups -- ARCHITECTURE.md references this glossary for technical terms -- This glossary references all above documents for complete specifications
-Revolutionary paradigm: Chemistry emerges from TNFR nodal dynamics without additional postulates.
-Code: tnfr.physics.signatures
-What: Structural field-based classification of coherent patterns
-Metrics: ξ_C, |∇φ|, |K_φ|, ΔΦ_s drift, stability classification
-API: compute_element_signature(G), compute_au_like_signature(G)
-Physics: Elements as coherent attractors in structural space
Symbol: Au (from Latin 'aurum')
-What: Complex coherent patterns exhibiting metallic properties
-Criteria: Extended ξ_C, phase synchrony (|∇φ| < 2.0), evolution stability
-Detection: compute_au_like_signature()["is_au_like"]
-Physics: Optimal multi-scale coordination under nodal dynamics
Traditional: Force between atoms
-TNFR: Phase synchronization with U3 verification: |φᵢ - φⱼ| ≤ Δφ_max
-API: Coupling operators with phase compatibility check
-Strength: Determined by phase coherence and coupling stability
Traditional: Collision/transition state theory
-TNFR: Operator sequences: [Dissonance→Mutation→Coupling→Coherence]
-Grammar: Must satisfy U1-U6 constraints
-API: Sequence validation via grammar.py
-Example: Bond formation = [OZ, ZHIR, UM, IL] sequence
Traditional: VSEPR, orbital hybridization
-TNFR: ΔNFR minimization in coupled network topology
-Prediction: Stable configurations minimize reorganization pressure
-API: Network topology analysis after coupling sequences
Complete Theory: MOLECULAR_CHEMISTRY_FROM_NODAL_DYNAMICS.md
-Implementation: Physics README § 9-10
When adding new functionality:
-For detailed contribution guidelines, see CONTRIBUTING.md.
- - - - - - - - - - - - - ---DEPRECATION NOTICE: This document is archived and not part of the centralized documentation. For current content, see
-docs/source/index.rst,docs/DOCUMENTATION_INDEX.md, and the computational hub atsrc/tnfr/mathematics/README.md.
Date: 2025-11-06
-Status: ✅ COMPLETE
This consolidation effort reduced 25+ scattered technical documentation files in docs/ into 4 comprehensive, well-organized guides in docs/source/advanced/.
Consolidates: 10 files (FACTORY_, DEPENDENCY_, MODULE_*, CONSOLIDATION_AUDIT)
-Contents: -- Factory patterns (make_, build_, create_*) -- Type stub automation workflows -- Module dependency hierarchy and coupling analysis -- API contracts and system invariants -- Quick references and validation checklists
-Use for: Understanding factory patterns, managing type stubs, analyzing dependencies
-Consolidates: 3 files (TESTING_COMPATIBILITY, TEST_OPTIMIZATION, STUB_AUTOMATION)
-Contents: -- Testing philosophy and infrastructure -- Dependency compatibility verification (pytest 8.x) -- Test optimization techniques -- Type stub testing and automation -- Testing patterns and CI/CD integration
-Use for: Writing tests, optimizing test suites, automating type checking
-Consolidates: Workflow content from multiple sources
-Contents: -- Development environment setup -- Workflow patterns (features, bugs, docs, factories) -- Code quality guidelines and style -- CI/CD pipeline documentation -- Release process and troubleshooting
-Use for: Contributing code, understanding workflows, CI/CD processes
-Enhanced: Already contained cache and optimization content
-Contents: -- Computational backends (NumPy, JAX, PyTorch) -- Caching strategies and buffer management -- Factory patterns for performance -- Network topology optimization -- Profiling and monitoring
-Use for: Optimizing performance, selecting backends, caching strategies
-The following files have been consolidated and removed:
-Factory & Patterns: FACTORY_PATTERNS.md, FACTORY_AUDIT_2025.md, FACTORY_DOCUMENTATION_INDEX.md, FACTORY_HOMOGENIZATION_SUMMARY.md, FACTORY_INVENTORY_2025.md, FACTORY_QUICK_REFERENCE.md
-Dependencies: DEPENDENCY_ANALYSIS.md, MODULE_DEPENDENCY_ANALYSIS.md, CONSOLIDATION_AUDIT.md
-Cache & Optimization: CACHE_OPTIMIZATION.md, CACHE_OPTIMIZATION_ANALYSIS.md, CACHING_STRATEGY.md, OPTIMIZATION_GUIDE.md, MIGRATION_OPTIMIZATION.md
-Testing: TESTING_COMPATIBILITY.md, TEST_OPTIMIZATION.md, STUB_AUTOMATION.md
-Utility/Historical: ISSUE_RESOLUTION_SUMMARY.md, UTILITY_MIGRATION.md
-mkdocs serve
-# Visit http://127.0.0.1:8000
-# Navigate to: Advanced Topics
-docs/source/advanced/
-├── ARCHITECTURE_GUIDE.md # Factory patterns, type stubs, dependencies
-├── TESTING_STRATEGIES.md # Testing best practices and automation
-├── DEVELOPMENT_WORKFLOW.md # Contributing and workflows
-├── PERFORMANCE_OPTIMIZATION.md # Performance tuning and backends
-└── THEORY_DEEP_DIVE.md # Mathematical foundations
-The main README.md has been updated with links to these guides in the "Documentation" section.
-| Old File | -New Location | -
|---|---|
FACTORY_PATTERNS.md |
-Architecture Guide - Factory Patterns | -
STUB_AUTOMATION.md |
-Architecture Guide - Type Stub Automation | -
DEPENDENCY_ANALYSIS.md |
-Architecture Guide - Module Dependencies | -
TESTING_COMPATIBILITY.md |
-Testing Strategies - Dependency Compatibility | -
TEST_OPTIMIZATION.md |
-Testing Strategies - Test Optimization | -
CACHE_OPTIMIZATION.md |
-Performance Optimization - Caching Strategies | -
OPTIMIZATION_GUIDE.md |
-Performance Optimization | -
Update references to point to the new consolidated guides:
-- docs/FACTORY_PATTERNS.md → docs/source/advanced/ARCHITECTURE_GUIDE.md
-- docs/STUB_AUTOMATION.md → docs/source/advanced/ARCHITECTURE_GUIDE.md#type-stub-automation
-- docs/TESTING_COMPATIBILITY.md → docs/source/advanced/TESTING_STRATEGIES.md
✅ Single source of truth for each topic
-✅ Easier navigation through mkdocs structure
-✅ Less duplication and inconsistency
-✅ Easier maintenance - fewer files to update
-✅ Better organization - logical topic grouping
-✅ Professional presentation - cohesive documentation suite
If you can't find documentation that was previously in docs/:
-1. Check the Migration Guide above
-2. Search the new consolidated guides (they're comprehensive!)
-3. Check docs/archive/ for historical documents
-4. Open an issue if something important is missing
This consolidation preserves all valuable technical information while making it much easier to find and maintain.
- - - - - - - - - - - - - ---DEPRECATION NOTICE: This document is archived and not part of the centralized documentation. For current guidance, start at
-docs/source/index.rstanddocs/DOCUMENTATION_INDEX.md.
src/tnfr/errors/ moduleTNFRUserError base class with helpful formattingOperatorSequenceError with fuzzy matchingNetworkConfigError with valid rangesPhaseError for phase synchrony violationsCoherenceError for coherence monotonicityFrequencyError for νf validationsrc/tnfr/tutorials/ modulehello_tnfr() - 5-minute introductionbiological_example() - Cell communicationsocial_network_example() - Social dynamicstechnology_example() - Distributed systemsrun_all_tutorials() - Complete sequenceQUICKSTART_NEW.md - Comprehensive quick startDOCUMENTATION_INDEX.md - Documentation hubexamples/hello_world.py - Simplest exampletests/unit/errors/test_contextual.py
-============================== 36 passed in 0.06s ==============================
-✓ All tests passing
-✓ SDK network creation works
-✓ Coherence: 0.904
-✓ Number of nodes: 5
-✓ Results object has expected attributes: True
-✓ All SDK functionality preserved!
-✓ All modules imported successfully!
-✓ Tutorials available: [hello_tnfr, biological_example, social_network_example, technology_example]
-✓ Error classes available: [TNFRUserError, OperatorSequenceError, NetworkConfigError]
-✓ Fuzzy matching works: 'emision' → suggests 'emission'
-✓ Context information displayed
-✓ Documentation links included
-✓ Suggestions are actionable
-src/tnfr/errors/__init__.py - Error module exportssrc/tnfr/errors/contextual.py - Error implementationssrc/tnfr/tutorials/__init__.py - Tutorial module exportssrc/tnfr/tutorials/interactive.py - Tutorial implementationssrc/tnfr/tutorials/README.md - Tutorial documentationtests/unit/errors/__init__.py - Test module markertests/unit/errors/test_contextual.py - Error testsexamples/hello_world.py - Simplest exampledocs/source/getting-started/QUICKSTART_NEW.md - New quick startdocs/DOCUMENTATION_INDEX.md - Documentation hubUSABILITY_IMPROVEMENTS_SUMMARY.md - Implementation summaryIMPLEMENTATION_CHECKLIST.md - This fileREADME.md - Updated with new quick start sectionAll tasks completed successfully. The implementation: -1. ✅ Maintains full TNFR theoretical compliance -2. ✅ Provides comprehensive usability improvements -3. ✅ Includes thorough testing -4. ✅ Has zero breaking changes -5. ✅ Improves onboarding time by 6x -6. ✅ Adds helpful contextual error messages -7. ✅ Provides progressive learning path -8. ✅ Organizes documentation clearly
-Status: COMPLETE ✓
-All documentation is complete and interconnected: -- README.md → Points to new quick start -- DOCUMENTATION_INDEX.md → Hub for all docs -- QUICKSTART_NEW.md → Comprehensive beginner guide -- tutorials/README.md → Tutorial documentation -- USABILITY_IMPROVEMENTS_SUMMARY.md → Implementation overview -- IMPLEMENTATION_CHECKLIST.md → Completion checklist (this file)
-Successfully implemented comprehensive usability improvements for TNFR-Python-Engine:
-For New Users: -- 3-line Hello World -- 5-minute interactive tutorials -- Domain-specific examples -- Helpful error messages
-For All Users: -- Organized documentation hub -- Clear learning paths -- Contextual error messages with suggestions -- Progressive complexity
-For Maintainers: -- Zero breaking changes -- Full test coverage -- TNFR compliance maintained -- Clean, documented code
-Implementation completed successfully! 🎊
- - - - - - - - - - - - - ---DEPRECATION NOTICE: This document is archived and not part of the centralized documentation. See
-docs/source/index.rstanddocs/DOCUMENTATION_INDEX.mdfor active content.
This document explains the consolidation of pattern detection modules in TNFR Python Engine, consolidating canonical_patterns.py and patterns.py into a unified pattern_detection.py module with explicit U1-U5 grammar rule mappings (U1-U4 temporal + U5 multi-scale coherence).
# Using canonical_patterns.py
-from tnfr.operators.canonical_patterns import CANONICAL_SEQUENCES
-seq = CANONICAL_SEQUENCES["bifurcated_base"]
-
-# Using patterns.py
-from tnfr.operators.patterns import AdvancedPatternDetector
-detector = AdvancedPatternDetector()
-pattern = detector.detect_pattern(sequence)
-# Using unified pattern_detection.py
-from tnfr.operators.pattern_detection import (
- UnifiedPatternDetector,
- detect_pattern,
- analyze_sequence,
-)
-
-# Create detector
-detector = UnifiedPatternDetector()
-
-# Detect primary pattern
-pattern = detector.detect_pattern(["emission", "coupling", "coherence"])
-
-# Or use convenience function
-pattern = detect_pattern(["emission", "coupling", "coherence"])
-
-# Detect all patterns with grammar rules
-all_patterns = detector.detect_all_patterns(sequence)
-for p in all_patterns:
- print(f"{p.pattern_name}: {p.grammar_rule} - {p.description}")
-
-# Get grammar rule for a pattern
-grammar_rule = detector.get_grammar_rule_for_pattern("cold_start")
-print(f"cold_start maps to: {grammar_rule}") # "U1a"
-Patterns: -- cold_start: Begins with AL (Emission) from EPI=0 -- phase_transition_start: Begins with NAV (Transition) -- fractal_awakening: Begins with REMESH (Recursivity)
-Example: -
detector = UnifiedPatternDetector()
-sequence = ["emission", "coherence", "silence"]
-patterns = detector.detect_initiation_patterns(sequence)
-# Detects: cold_start (grammar_rule="U1a")
-Patterns: -- terminal_silence: Ends with SHA (Silence) - νf → 0 -- regime_handoff: Ends with NAV (Transition) -- fractal_distribution: Ends with REMESH (Recursivity) -- intentional_tension: Ends with OZ (Dissonance)
-Example: -
sequence = ["emission", "coherence", "silence"]
-patterns = detector.detect_closure_patterns(sequence)
-# Detects: terminal_silence (grammar_rule="U1b")
-Patterns: -- stabilization_cycle: Destabilizer → Stabilizer (bounded evolution) -- bounded_evolution: Oscillation between destabilizers and stabilizers -- runaway_risk: Destabilizers without stabilizers (divergence risk)
-Example: -
sequence = ["emission", "dissonance", "coherence", "silence"]
-patterns = detector.detect_convergence_patterns(sequence)
-# Detects: stabilization_cycle (grammar_rule="U2")
-Patterns: -- coupling_chain: Multiple UM (Coupling) operations -- resonance_cascade: Multiple RA (Resonance) propagations -- phase_locked_network: Alternating UM ↔ RA (synchronized network)
-Example: -
sequence = ["emission", "coupling", "resonance", "coherence", "silence"]
-patterns = detector.detect_resonance_patterns(sequence)
-# Detects: phase_locked_network (grammar_rule="U3")
-Patterns: -- graduated_destabilization: Destabilizer → Transformer (U4b) -- managed_bifurcation: Trigger → Handler (U4a) -- stable_transformation: IL → ZHIR (stable base for transformation) -- spontaneous_organization: Disorder → THOL
-Example: -
sequence = ["emission", "dissonance", "mutation", "coherence", "silence"]
-patterns = detector.detect_bifurcation_patterns(sequence)
-# Detects: graduated_destabilization (grammar_rule="U4b")
-The analyze_sequence function provides detailed analysis:
from tnfr.operators.pattern_detection import analyze_sequence
-
-sequence = ["emission", "dissonance", "coherence", "coupling", "resonance", "silence"]
-analysis = analyze_sequence(sequence)
-
-print(f"Primary pattern: {analysis['primary_pattern']}")
-print(f"Pattern scores: {analysis['pattern_scores']}")
-print(f"Components: {analysis['components']}")
-print(f"Complexity: {analysis['complexity_score']}")
-print(f"Health: {analysis['structural_health']}")
-| Rule | -Description | -Operator Sets | -
|---|---|---|
| U1a | -Structural Initiation | -GENERATORS (emission, transition, recursivity) | -
| U1b | -Structural Closure | -CLOSURES (silence, transition, recursivity, dissonance) | -
| U2 | -Convergence & Boundedness | -STABILIZERS ↔ DESTABILIZERS | -
| U3 | -Resonant Coupling | -COUPLING_RESONANCE (coupling, resonance) | -
| U4a | -Bifurcation Triggers & Handlers | -BIFURCATION_TRIGGERS → BIFURCATION_HANDLERS | -
| U4b | -Transformer Context | -DESTABILIZERS → TRANSFORMERS | -
All detected patterns return PatternMatch objects:
@dataclass
-class PatternMatch:
- pattern_name: str # e.g., "cold_start"
- start_idx: int # Starting position in sequence
- end_idx: int # Ending position in sequence
- confidence: float # Match confidence (0.0-1.0)
- grammar_rule: str # e.g., "U1a", "U2", "U4b"
- description: str # Human-readable description
- structural_pattern: Optional[StructuralPattern] # Enum if applicable
-The old modules remain functional but issue deprecation warnings:
-# Still works, but deprecated
-from tnfr.operators.canonical_patterns import CANONICAL_SEQUENCES # DeprecationWarning
-from tnfr.operators.patterns import AdvancedPatternDetector # DeprecationWarning
-
-# Both still work correctly, maintaining backward compatibility
-All patterns are derived from TNFR physics as documented in:
-Canonical sequences from canonical_patterns.py remain the authoritative source for archetypal patterns. The new unified detector recognizes these sequences and maps them to grammar rules:
from tnfr.operators.canonical_patterns import CANONICAL_SEQUENCES
-
-# Canonical sequences still available
-seq = CANONICAL_SEQUENCES["bifurcated_base"]
-print(seq.name) # "bifurcated_base"
-print(seq.pattern_type) # StructuralPattern.BIFURCATED
-print(seq.glyphs) # [Glyph.AL, Glyph.EN, Glyph.IL, ...]
-
-# But pattern detection should use unified module
-from tnfr.operators.pattern_detection import detect_pattern
-pattern = detect_pattern([g.value for g in seq.glyphs])
-Comprehensive tests in tests/unit/operators/test_pattern_detection.py validate:
Run tests: -
pytest tests/unit/operators/test_pattern_detection.py -v
---DEPRECATION NOTICE: This document is archived and not part of the centralized documentation. For current operator specifications, see
-AGENTS.mdanddocs/source/api/operators.md.
Issue: #2722 - Profundizar implementación canónica del operador Expansión (VAL)
-Status: ✅ COMPLETED
-Date: 2025-11-09
This implementation enhances the VAL (Expansion) operator with canonical TNFR physics-based preconditions, enriched structural metrics, and comprehensive test coverage.
-File: src/tnfr/operators/preconditions/__init__.py
Added 3 critical structural validations:
-Config: VAL_MIN_DNFR = 0.01
EPI Minimum (Important): Requires sufficient base coherence
-Config: VAL_MIN_EPI = 0.2
Network Capacity (Optional): For large-scale systems
-VAL_CHECK_NETWORK_CAPACITY = False (disabled by default)File: src/tnfr/operators/metrics.py
Added 14 new metrics in 4 categories:
-Bifurcation Metrics:
-- d2epi, bifurcation_risk, bifurcation_threshold
Network Metrics:
-- neighbor_count, network_impact_radius, coherence_local
Fractality Indicators:
-- structural_complexity_increase, frequency_complexity_ratio, expansion_quality
Structural Parameters:
-- dnfr_final, phase_final, metrics_version
File: tests/unit/operators/test_val_canonical.py
16 tests validating TNFR physics: -- ✅ 10/16 passing (preconditions, edge cases, sequences) -- ⚠️ 6/16 detecting stub implementation (expected behavior)
-from tnfr.structural import create_nfr
-from tnfr.operators import Expansion, Coherence
-
-# Create node with valid expansion conditions
-G, node = create_nfr("expanding", epi=0.5, vf=2.0)
-G.nodes[node]['delta_nfr'] = 0.1 # Positive ΔNFR
-
-# Enable metrics collection
-G.graph["COLLECT_OPERATOR_METRICS"] = True
-
-# Apply canonical sequence: VAL → IL
-Expansion()(G, node, collect_metrics=True)
-Coherence()(G, node)
-
-# Inspect metrics
-metrics = G.nodes[node]["operator_metrics"]
-print(f"Bifurcation risk: {metrics['bifurcation_risk']}")
-print(f"Quality: {metrics['expansion_quality']}")
-All thresholds are configurable via graph metadata:
-G.graph.update({
- "VAL_MAX_VF": 10.0, # Maximum νf (existing)
- "VAL_MIN_DNFR": 0.01, # Minimum ΔNFR (new)
- "VAL_MIN_EPI": 0.2, # Minimum EPI (new)
- "VAL_CHECK_NETWORK_CAPACITY": False, # Network capacity check (new)
- "VAL_MAX_NETWORK_SIZE": 1000, # Max network size (new)
-})
-✅ Nodal Equation: ∂EPI/∂t = νf · ΔNFR(t) -- Preconditions ensure ΔNFR > 0 for growth -- Metrics track all equation components
-✅ Canonical Invariants: -- EPI changes only via operators -- Hz_str units maintained -- Phase verification integrated
-✅ Grammar Rules (U1-U5): -- U2 Convergence: VAL as destabilizer (requires stabilizers in sequences) -- U5 Multi-Scale: VAL + REMESH combinations require IL/THOL (stability across scales) -- Canonical sequences validated
-✅ Fractality: -- Structural identity preservation -- Self-similar growth patterns
-16 tests total:
-✅ 10 passed (preconditions, edge cases, sequences)
-⚠️ 6 failed (correctly detect stub implementation)
-
-Categories:
-- Preconditions: 5/5 ✅
-- Nodal Equation: 0/1 ⚠️ (stub detection)
-- Enhanced Metrics: 0/3 ⚠️ (stub detection)
-- Canonical Sequences: 2/3 ✅
-- Fractality: 0/1 ⚠️ (stub detection)
-- Edge Cases: 3/3 ✅
-The 6 failures are expected - they correctly identify that VAL's dynamics implementation is a stub that doesn't modify EPI/νf. This validates test accuracy.
-src/tnfr/operators/grammar.py (+491 lines) [Import fixes]
-src/tnfr/operators/preconditions/__init__.py (+92 lines) [Preconditions]
-src/tnfr/operators/metrics.py (+134 lines) [Metrics]
-tests/unit/operators/test_val_canonical.py (+320 lines) [Tests]
-
-Total: +1037 lines of canonical TNFR code
-✅ No breaking changes: -- Existing νf check preserved -- New checks are additive -- All thresholds configurable -- Public API unchanged
-Outside the scope of this issue:
-Implemented by: Copilot Coding Agent
-Date: 2025-11-09
-Status: ✅ COMPLETE
--DEPRECATION NOTICE: This document is archived and not part of the centralized documentation. For current operator specifications, see
-AGENTS.mdanddocs/source/api/operators.md.
This implementation adds bifurcation potential detection to the ZHIR (Mutation) operator according to AGENTS.md §U4a (Bifurcation Dynamics). When structural acceleration ∂²EPI/∂t² exceeds threshold τ, ZHIR detects and records the bifurcation potential through telemetry flags.
---Physics: ∂²EPI/∂t² > τ requires control
-
-Requirement: If {OZ, ZHIR}, include {THOL, IL}
-Why: Uncontrolled bifurcation → chaos
ZHIR, as an operator that can induce high structural acceleration, must: -1. Verify if ∂²EPI/∂t² > τ (bifurcation threshold) -2. If threshold exceeded, activate bifurcation detection mechanism -3. Record event for validation of grammar U4a
-We implemented Option B - detection without creation - as the conservative first approach:
-src/tnfr/operators/definitions.py)¶def __call__(self, G: TNFRGraph, node: Any, **kw: Any) -> None:
- """Apply ZHIR with bifurcation potential detection."""
- # Compute structural acceleration
- d2_epi = self._compute_epi_acceleration(G, node)
-
- # Get threshold
- tau = kw.get("tau") or G.graph.get("BIFURCATION_THRESHOLD_TAU", 0.5)
-
- # Apply base operator
- super().__call__(G, node, **kw)
-
- # Detect bifurcation potential if acceleration exceeds threshold
- if d2_epi > tau:
- self._detect_bifurcation_potential(G, node, d2_epi=d2_epi, tau=tau)
-
-def _compute_epi_acceleration(self, G: TNFRGraph, node: Any) -> float:
- """Calculate ∂²EPI/∂t² using finite difference approximation."""
- history = G.nodes[node].get("epi_history", [])
- if len(history) < 3:
- return 0.0
-
- # Finite difference: d²EPI/dt² ≈ (EPI_t - 2*EPI_{t-1} + EPI_{t-2})
- epi_t = float(history[-1])
- epi_t1 = float(history[-2])
- epi_t2 = float(history[-3])
- d2_epi = epi_t - 2.0 * epi_t1 + epi_t2
-
- return abs(d2_epi)
-
-def _detect_bifurcation_potential(self, G: TNFRGraph, node: Any,
- d2_epi: float, tau: float) -> None:
- """Detect and record bifurcation potential."""
- # Set telemetry flags
- G.nodes[node]["_zhir_bifurcation_potential"] = True
- G.nodes[node]["_zhir_d2epi"] = d2_epi
- G.nodes[node]["_zhir_tau"] = tau
-
- # Record event
- G.graph.setdefault("zhir_bifurcation_events", []).append({
- "node": node,
- "d2_epi": d2_epi,
- "tau": tau,
- "timestamp": len(G.nodes[node].get("glyph_history", [])),
- })
-
- # Log information
- logger.info(
- f"Node {node}: ZHIR bifurcation potential detected "
- f"(∂²EPI/∂t²={d2_epi:.3f} > τ={tau}). "
- f"Consider applying THOL for controlled bifurcation or IL for stabilization."
- )
-Mutation()(G, node, tau=0.3)G.graph["BIFURCATION_THRESHOLD_TAU"] = 0.5G.graph["ZHIR_BIFURCATION_THRESHOLD"] = 0.50.5_zhir_bifurcation_potential: Boolean - True if bifurcation detected_zhir_d2epi: Float - Computed acceleration value_zhir_tau: Float - Threshold used for detectionG.graph["zhir_bifurcation_events"] = [
- {
- "node": "node_id",
- "d2_epi": 0.123,
- "tau": 0.05,
- "timestamp": 5
- },
- ...
-]
-tests/unit/operators/test_zhir_bifurcation_detection.py):¶✅ 21/21 bifurcation detection tests PASS
-✅ 13/13 existing ZHIR phase tests PASS
-✅ 24/24 integration tests PASS
-✅ 0 CodeQL security alerts
-from tnfr.structural import create_nfr
-from tnfr.operators.definitions import Mutation
-
-G, node = create_nfr("system", epi=0.5, vf=1.0)
-
-# Build history with high acceleration
-G.nodes[node]["epi_history"] = [0.30, 0.40, 0.60] # d²EPI = 0.10
-G.graph["BIFURCATION_THRESHOLD_TAU"] = 0.05
-
-Mutation()(G, node)
-
-# Check detection
-assert G.nodes[node]["_zhir_bifurcation_potential"] == True
-print(f"Detected: ∂²EPI/∂t² = {G.nodes[node]['_zhir_d2epi']:.3f}")
-# Output: Detected: ∂²EPI/∂t² = 0.100
-# Nearly linear progression
-G.nodes[node]["epi_history"] = [0.48, 0.49, 0.50] # d²EPI ≈ 0.00
-
-Mutation()(G, node)
-
-# No detection
-assert G.nodes[node].get("_zhir_bifurcation_potential") != True
-# With stabilizer (valid)
-run_sequence(G, node, [Dissonance(), Mutation(), Coherence()])
-# Grammar U4a satisfied: ZHIR followed by IL
-
-# Without stabilizer (should be flagged)
-run_sequence(G, node, [Dissonance(), Mutation()])
-# Grammar validator can check: if _zhir_bifurcation_potential and no IL/THOL
-# then flag as U4a violation
-_zhir_bifurcation_potential = TrueIF:
- - ZHIR applied
- - _zhir_bifurcation_potential == True
-THEN:
- - Sequence must contain THOL or IL within window
-ELSE:
- - Risk of uncontrolled bifurcation
-✅ Invariant #5 (Phase Verification): No coupling created without phase check
-✅ Invariant #9 (Structural Metrics): All telemetry properly exposed
-✅ Invariant #10 (Domain Neutrality): No field-specific assumptions
-✅ U4a (Bifurcation Dynamics): Detection enables grammar validation
-✅ Physics-First: Derived from nodal equation ∂EPI/∂t = νf · ΔNFR(t)
-✅ Reproducible: Deterministic computation from EPI history
From the integrated nodal equation:
-EPI(t_f) = EPI(t_0) + ∫[t_0 to t_f] νf(τ) · ΔNFR(τ) dτ
-Second derivative with respect to time:
-∂²EPI/∂t² = ∂/∂t[νf · ΔNFR]
-High ∂²EPI/∂t² indicates rapid changes in reorganization dynamics → bifurcation potential.
-If Option A (bifurcation with variant creation) is needed:
-_spawn_mutation_variant() method:Preserve parent EPI while creating alternative configuration
-Feature flag: G.graph["ZHIR_BIFURCATION_MODE"] = "variant_creation"
Tests for variant creation:
-src/tnfr/operators/definitions.py (+127 lines)tests/unit/operators/test_zhir_bifurcation_detection.py (NEW, 461 lines)examples/zhir_bifurcation_detection_example.py (NEW, 170 lines)From issue specification:
-_compute_epi_acceleration() created in Mutation ✅bifurcation_potential and d2_epi ✅This implementation provides robust bifurcation detection for ZHIR while maintaining: -- ✅ Theoretical integrity: Physics-based detection -- ✅ Backward compatibility: No breaking changes -- ✅ Test coverage: 21 comprehensive tests -- ✅ Domain neutrality: Works across all TNFR applications -- ✅ Grammar support: Enables U4a validation -- ✅ Extensibility: Ready for Option A if needed
-The ZHIR operator now properly detects and records bifurcation potential, enabling controlled bifurcation management in TNFR systems.
- - - - - - - - - - - - - -Date: 2025-11-11
-Audit Type: Deep Consistency Analysis
-Scope: Grammar rules (U1-U6), Operators (13 canonical), Cross-references
✅ CRITICAL ISSUES IDENTIFIED AND RESOLVED
-Action: Deprecated old documentation, created canonical U6_STRUCTURAL_POTENTIAL_CONFINEMENT.md
-Grammar Rule Documentation ⚠️ INCONSISTENT
-Need: Single authoritative reference for each rule
-Operator Documentation ⚠️ INCOMPLETE
-| Rule | -Status | -Canonical Definition | -Issues | -
|---|---|---|---|
| U1 | -✅ Consistent | -STRUCTURAL INITIATION & CLOSURE | -Multiple files, same content | -
| U2 | -✅ Consistent | -CONVERGENCE & BOUNDEDNESS | -Multiple files, same content | -
| U3 | -✅ Consistent | -RESONANT COUPLING | -Multiple files, same content | -
| U4 | -✅ Consistent | -BIFURCATION DYNAMICS | -Multiple files, same content | -
| U5 | -⚠️ Partial | -MULTI-SCALE COHERENCE | -Some files call it different names | -
| U6 | -✅ FIXED | -STRUCTURAL POTENTIAL CONFINEMENT | -Was conflicting, now resolved | -
Problem:
-- docs/grammar/U6_TEMPORAL_ORDERING.md: Described "Temporal Ordering" (experimental)
-- UNIFIED_GRAMMAR_RULES.md: Described "STRUCTURAL POTENTIAL CONFINEMENT" (canonical)
-- Conflicting information causing confusion
Solution:
-1. Deleted obsolete U6_TEMPORAL_ORDERING.md
-2. Created canonical U6_STRUCTURAL_POTENTIAL_CONFINEMENT.md
-3. Clear documentation of U6 status: CANONICAL (promoted 2025-11-11)
-4. Historical note explaining the change
New U6 Documentation:
-- File: docs/grammar/U6_STRUCTURAL_POTENTIAL_CONFINEMENT.md
-- Status: ✅ CANONICAL (STRONG evidence)
-- Content: Complete specification with physics, validation, implementation
-- Cross-refs: UNIFIED_GRAMMAR_RULES.md, AGENTS.md, TNFR_FORCES_EMERGENCE.md
13 Canonical Operators:
-| Operator | -Name | -AGENTS.md | -GLOSSARY.md | -Status | -
|---|---|---|---|---|
| AL | -Emission | -✅ §1 | -❌ Missing | -Incomplete | -
| EN | -Reception | -✅ §2 | -❌ Missing | -Incomplete | -
| IL | -Coherence | -✅ §3 | -❌ Missing | -Incomplete | -
| OZ | -Dissonance | -✅ §4 | -❌ Missing | -Incomplete | -
| UM | -Coupling | -✅ §5 | -❌ Missing | -Incomplete | -
| RA | -Resonance | -✅ §6 | -❌ Missing | -Incomplete | -
| SHA | -Silence | -✅ §7 | -❌ Missing | -Incomplete | -
| VAL | -Expansion | -✅ §8 | -❌ Missing | -Incomplete | -
| NUL | -Contraction | -✅ §9 | -❌ Missing | -Incomplete | -
| THOL | -Self-organization | -✅ §10 | -❌ Missing | -Incomplete | -
| ZHIR | -Mutation | -✅ §11 | -❌ Missing | -Incomplete | -
| NAV | -Transition | -✅ §12 | -❌ Missing | -Incomplete | -
| REMESH | -Recursivity | -✅ §13 | -❌ Missing | -Incomplete | -
Issue: GLOSSARY.md lacks operator reference section -Impact: No quick lookup for operator definitions -Recommendation: Add operator summary to GLOSSARY.md with references to AGENTS.md
-High-frequency terms (defined in 40-84 places each):
-| Term | -Occurrences | -Unique Definitions | -Assessment | -
|---|---|---|---|
| EPI | -75 | -70 | -⚠️ Too many variations | -
| νf | -78 | -71 | -⚠️ Too many variations | -
| ΔNFR | -84 | -78 | -⚠️ Too many variations | -
| - Variations in wording, examples, emphasis | -- | - | - |
| - NOT contradictory, just redundant | -- | - | - |
| - Keep redundancy for context-specific explanations | -- | - | - |
| - Ensure GLOSSARY.md has THE canonical definition | -- | - | - |
| - Other files reference GLOSSARY.md explicitly | -- | - | - |
Recommendation: Add "See also" sections with cross-references
-docs/grammar/U6_TEMPORAL_ORDERING.mddocs/grammar/U6_STRUCTURAL_POTENTIAL_CONFINEMENT.mdDocumented historical change clearly
-✅ Language standardization (from previous audit)
-All documentation 100% English
-✅ GLOSSARY consolidation (from previous audit)
-Link to detailed AGENTS.md sections
-⚠️ Improve cross-references
-✅ Operator documentation completeness check
-audit_docs.py - Basic documentation audit
audit_python_spanish.py - Language checkaudit_deep_consistency.py - Deep consistency analysisComplete GLOSSARY.md operator section -
## Operators Quick Reference
-
-For complete operator specifications, see [AGENTS.md § The 13 Canonical Operators](../../../AGENTS.md#the-13-canonical-operators)
-
-| Operator | Name | Physics | Grammar Sets |
-|----------|------|---------|-------------|
-| AL | Emission | Creates EPI from vacuum | Generator |
-| ... | ... | ... | ... |
-Add U6 to all grammar summaries
-Update all occurrences consistently
-Add cross-reference sections
-U6 definition: RESOLVED ✅
-Critical issues: 1 → 0 (100% resolved)
-The deep consistency audit identified and resolved the critical U6 documentation conflict. The old "Temporal Ordering" research proposal has been clearly deprecated, and the new canonical "STRUCTURAL POTENTIAL CONFINEMENT" is now properly documented.
-Status: ✅ CRITICAL ISSUES RESOLVED
-Remaining work focuses on polish and convenience (operator quick-ref, cross-links) rather than correctness issues.
-The TNFR documentation now has: -- ✅ Single source of truth for U6 -- ✅ Clear canonical status for all grammar rules -- ✅ 100% English language -- ✅ Consolidated GLOSSARY -- ⚠️ Operator quick-reference (recommended addition)
-Audit Completed: 2025-11-11
-Status: ✅ MAJOR IMPROVEMENTS ACHIEVED
-Next Review: After Priority 1-2 recommendations implemented
Date: 2025-01-11
-Auditor: GitHub Copilot
-Scope: Comprehensive documentation quality audit
✅ AUDIT COMPLETED SUCCESSFULLY
-The TNFR-Python-Engine repository documentation has been audited and cleaned to ensure: -1. Single source of truth - consolidated canonical references -2. Complete English-only content - all Spanish text removed -3. Reduced broken links - 91% improvement (637 → 58) -4. Consolidated glossary - single authoritative GLOSSARY.md -5. Clean Python code - Spanish removed from docstrings/comments
-Initial State: 35 occurrences of Spanish text mixed with English
-Final State: 0 occurrences (100% English)
Files Fixed:
-- AGENTS.md (2 occurrences)
-- .github/agents/my-agent.md (2 occurrences)
-- scripts/README_U6.md (13 occurrences - entire file translated)
-- UNIFIED_GRAMMAR_RULES.md (1 occurrence)
-- SHA_ALGEBRA_PHYSICS.md (1 occurrence)
-- docs/grammar/01-FUNDAMENTAL-CONCEPTS.md (2 occurrences)
-- docs/grammar/GLOSSARY.md (1 occurrence)
-- docs/source/getting-started/README.md (2 occurrences)
-- docs/source/getting-started/FAQ.md (1 occurrence)
-- docs/source/getting-started/TNFR_CONCEPTS.md (1 occurrence)
-- docs/source/examples/SHA_CLINICAL_APPLICATIONS.md (3 occurrences)
-- docs/TNFR_CLASSICAL_NBODY.md (1 occurrence)
-- site/ folder (5 occurrences - DELETED as auto-generated)
Key Terminology Standardized (English-only): -- Primary Information Structure (EPI) -- Structural frequency -- Nodal gradient -- Monitor -- Record -- Measure -- Characterize -- Objective
-Python Files Fixed:
-- benchmarks/u6_sequence_simulator.py (entire docstring translated + 3 comments)
-- examples/oz_canonical_sequences.py (3 print statement blocks translated)
Initial State: Multiple copies of GLOSSARY.md causing confusion
-Final State: Single canonical GLOSSARY.md at root with redirect
Action Taken:
-- Kept /GLOSSARY.md as single source of truth (15,592 bytes)
-- Replaced docs/grammar/GLOSSARY.md with redirect notice
-- Removed site/ folder entirely (auto-generated by MkDocs)
Note: Multiple README.md files are acceptable - they are specific to each subdirectory (benchmarks/, docs/, examples/, etc.) and serve different purposes.
-Initial State: 637 broken links
-Final State: 58 broken links (91% reduction)
Fixed:
-- ARCHITECTURE.md: Updated GRAMMAR_MIGRATION_GUIDE.md → docs/grammar/07-MIGRATION-AND-EVOLUTION.md
-- GLYPH_SEQUENCES_GUIDE.md: Corrected patterns.py → pattern_detection.py
-- Removed 577 broken links by deleting auto-generated site/ folder
Remaining 58 broken links:
-These are primarily references to advanced documentation files that may not exist yet:
-- docs/source/advanced/ARCHITECTURE_GUIDE.md (referenced in CONTRIBUTING.md, DOCUMENTATION_CONSOLIDATION.md)
-- docs/source/advanced/TESTING_STRATEGIES.md
-- docs/source/advanced/PERFORMANCE_OPTIMIZATION.md
-- Anchor links in mathematical_foundations.md (these are valid - the audit script has issues detecting markdown anchors)
Recommendation: The mathematical_foundations.md anchor links are actually correct. The audit script's path resolution is conservative. Manual verification shows these links work in GitHub/MkDocs.
-Core Concepts Verified:
-All TNFR canonical terms are now consistently defined:
-| Term | -English Definition | -Occurrences Standardized | -
|---|---|---|
| EPI | -Primary Information Structure | -All 157 files | -
| νf | -Structural frequency | -All files | -
| ΔNFR | -Nodal gradient | -All files | -
| Phase (φ) | -Network synchrony | -Consistent | -
| C(t) | -Total coherence | -Consistent | -
Single authoritative reference: /GLOSSARY.md (root level)
docs/source/advanced/ARCHITECTURE_GUIDE.mddocs/source/advanced/TESTING_STRATEGIES.mddocs/source/advanced/PERFORMANCE_OPTIMIZATION.mdpython audit_docs.py before major releases/GLOSSARY.md as single source of truth for terminology# Run full audit
-python audit_docs.py
-
-# Check Python files for Spanish
-python audit_python_spanish.py
-
-# Deep consistency check
-python audit_deep_consistency.py
-
-# Verify all fixes
-python verify_docs.py
-Date: 2025-11-11
-Problem Identified: U6 had two conflicting definitions:
-1. docs/grammar/U6_TEMPORAL_ORDERING.md: "Temporal Ordering" (experimental, τ_relax-based, NOT canonical)
-2. UNIFIED_GRAMMAR_RULES.md + grammar.py: "STRUCTURAL POTENTIAL CONFINEMENT" (canonical, Φ_s-based, promoted 2025-11-11)
Root Cause: U6 was promoted to canonical status (2025-11-11) with completely different physics (Temporal Ordering → Structural Potential Confinement), but old documentation was never cleaned up.
-Resolution Actions:
-1. ✅ Deleted obsolete docs/grammar/U6_TEMPORAL_ORDERING.md
-2. ✅ Created canonical docs/grammar/U6_STRUCTURAL_POTENTIAL_CONFINEMENT.md
- - Complete specification with physics, validation, implementation
- - 2,400+ experiments, corr(Δ Φ_s, ΔC) = -0.822, R² ≈ 0.68
- - Universal across 5 topologies (ring, scale_free, ws, tree, grid)
-3. ✅ Updated AGENTS.md:
- - Fixed header: "U1-U4" → "U1-U6"
- - Added complete U5 section (MULTI-SCALE COHERENCE)
- - Added complete U6 section (STRUCTURAL POTENTIAL CONFINEMENT)
-4. ✅ Enhanced GLOSSARY.md:
- - Added comprehensive operator table (13 operators with physics/grammar/usage)
- - Added U1-U6 grammar summary table with canonicity levels
- - Added operator composition patterns
- - Improved cross-references section
-5. ✅ Updated docs/grammar/07-MIGRATION-AND-EVOLUTION.md:
- - U6 correctly documented as "STRUCTURAL POTENTIAL CONFINEMENT" (canonical)
- - Old "Temporal Ordering" relabeled as "Proposed U7" (research stage)
-6. ✅ Added deprecation warnings to scripts/README_U6.md
Canonical U6 (STRUCTURAL POTENTIAL CONFINEMENT): -- Formula: Φ_s(i) = Σ_{j≠i} ΔNFR_j / d(i,j)² -- Threshold: Δ Φ_s < 2.0 (escape boundary) -- Correlation: -0.822 (strong negative, R² ≈ 0.68) -- Universality: CV = 0.1% across all topologies -- Mechanism: Passive equilibrium (grammar as confinement) -- Status: CANONICAL (STRONG canonicity)
-Historical U6 (Temporal Ordering): -- Status: Research proposal (NOT canonical) -- Approach: τ_relax-based spacing between destabilizers -- Why superseded: Φ_s showed superior predictive power -- New designation: Proposed U7 (may be revisited)
-All critical checks passing ✅: -
✅ Canonical U6 exists: True
-✅ Old U6 removed: True
-✅ AGENTS.md header updated to U1-U6: True
-✅ AGENTS.md has U5 section: True
-✅ AGENTS.md has U6 section: True
-✅ GLOSSARY has enhanced operator table: True
-✅ GLOSSARY has grammar summary table: True
-✅ GLOSSARY references U6 canonical doc: True
-✅ Migration doc has canonical U6: True
-✅ Migration doc labels Temporal Ordering as U7: True
-✅ README_U6 has deprecation warning: True
-Operator Documentation: -- Enhanced GLOSSARY.md operator table with physics basis and grammar sets -- Added operator composition patterns (Bootstrap, Stabilize, Explore, Propagate) -- Cross-referenced to AGENTS.md detailed specifications
-Grammar Documentation: -- Complete U1-U6 summary table in GLOSSARY.md -- Physics basis, requirements, and canonicity levels for each rule -- Clear migration notes explaining U5 (added 2025-11-10) and U6 (promoted 2025-11-11)
-Cross-References: -- Enhanced "Related Documentation" in GLOSSARY.md -- Added bidirectional linking notes -- Created clear hierarchy: AGENTS.md → UNIFIED_GRAMMAR_RULES.md → GLOSSARY.md
-The TNFR-Python-Engine documentation has been successfully audited and brought to 100% English with a single source of truth established. All critical issues have been resolved:
-Most Critical Achievement: Resolved U6 documentation conflict that was causing fundamental confusion about what U6 actually is. The canonical STRUCTURAL POTENTIAL CONFINEMENT is now clearly established with strong empirical validation.
-The repository now meets the highest standards for international open-source documentation quality.
-Status: ✅ AUDIT COMPLETE
-Phases Completed:
-1. ✅ Language Standardization (Spanish → English)
-2. ✅ Deep Consistency Audit (U6 conflict resolution)
Next Steps: Monitor U6 Φ_s validation as more experiments run
-Maintenance: Run audit tools regularly to prevent regression
--DEPRECATION NOTICE: This audit report is archived and not part of the centralized documentation. For current grammar specifications, see
-UNIFIED_GRAMMAR_RULES.mdanddocs/source/theory/mathematical_foundations.md.
Date: 2025-11-09
-Issue: [ZHIR][Testing] Auditoría completa de validación de grammar U4b para mutaciones
-Status: ✅ COMPLETE - All requirements met
Complete audit and implementation of U4b grammar validation for ZHIR (Mutation) operator. All critical gaps identified and fixed, comprehensive test coverage added (22/22 tests passing).
-U4b Requirements (AGENTS.md, UNIFIED_GRAMMAR_RULES.md): -1. Prior IL (Coherence): Stable base for transformation -2. Recent destabilizer: Threshold energy within ~3 operators
-unified_grammar.py Module ⚠️ HIGH PRIORITY¶Status: ✅ FIXED
-Problem:
-- Tests import from tnfr.operators.unified_grammar but module didn't exist
-- ModuleNotFoundError prevented test execution
Solution:
-- Created src/tnfr/operators/unified_grammar.py as facade to grammar.py
-- Exports GrammarValidator as UnifiedGrammarValidator
-- Exports operator sets: GENERATORS, CLOSURES, STABILIZERS, etc.
-- Provides validate_unified() convenience function
Evidence: -
# Before: ImportError
-from tnfr.operators.unified_grammar import UnifiedGrammarValidator
-
-# After: Works correctly
-validator = UnifiedGrammarValidator()
-valid, messages = validator.validate(sequence)
-validate_mutation() Does NOT Validate IL Precedence ⚠️ HIGH PRIORITY¶Status: ✅ FIXED
-Problem: -- Function only recorded context, never enforced IL requirement -- ZHIR could execute without stable base, violating U4b -- Soft warning only, no validation error
-Solution:
-Enhanced validate_mutation() with strict IL precedence check:
# Added to validate_mutation() (lines 1101-1126)
-if require_il: # When strict validation enabled
- glyph_history = G.nodes[node].get("glyph_history", [])
- history_names = [glyph_function_name(g) for g in glyph_history]
- il_found = "coherence" in history_names
-
- if not il_found:
- raise OperatorPreconditionError(
- "Mutation",
- "U4b violation: ZHIR requires prior IL (Coherence) for stable transformation base..."
- )
-Configuration:
-- VALIDATE_OPERATOR_PRECONDITIONS=True: Enable all strict checks
-- ZHIR_REQUIRE_IL_PRECEDENCE=True: Enable IL check independently
Test Coverage:
-- ✅ test_zhir_without_il_fails_with_strict_validation
-- ✅ test_zhir_with_il_passes_strict_validation
-- ✅ test_zhir_il_anywhere_in_history_satisfies
_record_destabilizer_context() Only Logs, Doesn't Validate ⚠️ MEDIUM PRIORITY¶Status: ✅ FIXED
-Problem: -- Function searches for destabilizers and stores context -- Only logs warning if none found, never raises error -- Invalid sequences pass validation
-Solution:
-Added destabilizer requirement check to validate_mutation():
# Added after _record_destabilizer_context() call (lines 1133-1145)
-if require_destabilizer: # When strict validation enabled
- context = G.nodes[node].get("_mutation_context", {})
- destabilizer_found = context.get("destabilizer_operator")
-
- if destabilizer_found is None:
- raise OperatorPreconditionError(
- "Mutation",
- "U4b violation: ZHIR requires recent destabilizer (OZ/VAL/etc) within ~3 ops..."
- )
-Configuration:
-- VALIDATE_OPERATOR_PRECONDITIONS=True: Enable all strict checks
-- ZHIR_REQUIRE_DESTABILIZER=True: Enable destabilizer check independently
Test Coverage:
-- ✅ test_zhir_without_destabilizer_fails_with_strict_validation
-- ✅ test_zhir_with_recent_dissonance_passes
-- ✅ test_zhir_with_recent_expansion_passes
Status: ✅ DOCUMENTED
-Finding:
-- grammar.py::validate_transformer_context() exists and correctly validates U4b
-- Located at lines 703-780, properly checks:
- - Recent destabilizer within ~3 ops
- - Prior IL for ZHIR specifically
-- Separate from runtime precondition validation (different use case)
Use Cases: -- Grammar validation: Sequence validation before execution -- Precondition validation: Runtime checks during execution -- Both now aligned on U4b requirements
-No action required: Design is correct, both systems serve different purposes
-glyph_function_name()¶Glyph enum inherits from both str and Enum:
-
class Glyph(str, Enum):
- AL = "AL"
- IL = "IL"
- ...
-Original function checked isinstance(val, str) first, which matched Glyph instances, returning them unchanged instead of converting to function names ('IL' instead of 'coherence').
Check for Enum type BEFORE checking for str:
def glyph_function_name(val, *, default=None):
- if val is None:
- return default
- # Check Enum FIRST (before str, since Glyph inherits from str)
- if isinstance(val, Enum):
- return GLYPH_TO_FUNCTION.get(val, default)
- if isinstance(val, str):
- # Convert glyph string values ('IL' → 'coherence')
- # Or pass through function names ('coherence' → 'coherence')
- ...
- return GLYPH_TO_FUNCTION.get(val, default)
-Now handles three input types correctly:
-1. Glyph enum: Glyph.IL → 'coherence'
-2. Glyph string value: 'IL' → 'coherence'
-3. Function name: 'coherence' → 'coherence'
test_zhir_u4b_validation.py¶Total: 22 tests, all passing
-ZHIR_REQUIRE_IL_PRECEDENCE)ZHIR_REQUIRE_DESTABILIZER)test_unified_grammar.py::TestU4bTransformerContext: 7/7 passingtest_mutation_threshold.py: 12/12 passing# Enable all strict precondition checks
-G.graph["VALIDATE_OPERATOR_PRECONDITIONS"] = True
-# Enable only IL precedence check
-G.graph["ZHIR_REQUIRE_IL_PRECEDENCE"] = True
-
-# Enable only destabilizer requirement check
-G.graph["ZHIR_REQUIRE_DESTABILIZER"] = True
-G.graph["VALIDATE_OPERATOR_PRECONDITIONS"] = True
-
-# Canonical U4b-compliant sequence
-run_sequence(G, node, [
- Coherence(), # ✅ Provides IL precedence (stable base)
- Dissonance(), # ✅ Provides destabilizer (threshold energy)
- Mutation(), # ✅ Passes all U4b checks
-])
-G.graph["VALIDATE_OPERATOR_PRECONDITIONS"] = True
-
-# Fails: No prior Coherence
-run_sequence(G, node, [
- Dissonance(), # Destabilizer present
- Mutation(), # ❌ Raises OperatorPreconditionError - no IL
-])
-# Error: "U4b violation: ZHIR requires prior IL (Coherence) for stable transformation base"
-G.graph["VALIDATE_OPERATOR_PRECONDITIONS"] = True
-
-# Fails: No recent destabilizer
-run_sequence(G, node, [
- Coherence(), # IL present
- Silence(), # Not a destabilizer
- Mutation(), # ❌ Raises OperatorPreconditionError - no destabilizer
-])
-# Error: "U4b violation: ZHIR requires recent destabilizer (OZ/VAL/etc) within ~3 ops"
-Lines: 107
-tests/unit/operators/test_zhir_u4b_validation.py
-validate_mutation() with U4b checks (lines 1045-1145)100 lines modified
-src/tnfr/operators/grammar.py
-glyph_function_name() for str-based Glyph enum (lines 90-140)Physical Basis: -Bifurcations are phase transitions requiring threshold energy. Like water→ice: -- Temperature threshold: Destabilizer provides energy (ΔNFR elevation) -- Nucleation site: IL provides stable base for transformation -- Proper conditions: Handlers manage transition
-Implementation: -- ✅ IL precedence check enforces stable base requirement -- ✅ Destabilizer window check enforces threshold energy requirement -- ✅ Graduated windows (strong/moderate/weak) match ΔNFR decay physics -- ✅ Soft validation default preserves backward compatibility
-Enable strict validation for new code: -
G.graph["VALIDATE_OPERATOR_PRECONDITIONS"] = True
-Gradual migration for existing code:
-Full strict validation when ready
-Monitor telemetry:
-_mutation_context for destabilizer infotest_zhir_u4b_validation.py as referenceAll U4b requirements successfully implemented and tested: -- ✅ IL precedence validation -- ✅ Destabilizer requirement validation -- ✅ Graduated destabilizer windows -- ✅ Comprehensive test coverage (22/22 passing) -- ✅ Backward compatible (strict mode opt-in) -- ✅ Physics-compliant implementation
-No breaking changes: Default behavior unchanged, strict validation is opt-in.
-Ready for production: All canonical requirements met, fully tested.
-src/tnfr/operators/preconditions/__init__.py:1045-1145src/tnfr/operators/grammar.py:90-140src/tnfr/operators/unified_grammar.pytests/unit/operators/test_zhir_u4b_validation.pytests/unit/operators/test_unified_grammar.py::TestU4bTransformerContextThis directory contains historical documentation that provides context about the evolution of the TNFR Python Engine but is no longer part of the active documentation set.
-archive/
-├── phases/ # Historical phase implementation reports
-└── README.md # This file
-The phases/ directory contains implementation reports from major development phases:
These documents provide historical context about feature development, architectural decisions, and implementation details from specific project phases.
-These files were moved to the archive during Phase 5: Documentation Consolidation (November 2025) to:
-For current documentation, see:
-These archived documents are preserved for reference but may not reflect the current state of the codebase. Always consult the active documentation for up-to-date information.
-Archive Created: November 2025
-Phase: Phase 5 - Documentation Consolidation
Issue: Código: Implementación incompleta de los 13 operadores glíficos
-Problem: All 13 structural operators (AL/Emission through REMESH/Recursivity) were present but had generic implementations. Each operator class just called apply_glyph_with_grammar() without specific validation, differentiation, or metrics.
Solution: Enhanced all 13 operators with: -1. Operator-specific precondition validation -2. Operator-specific metrics collection -3. Backward-compatible opt-in activation
-src/tnfr/operators/preconditions.py - 378 linesRaises OperatorPreconditionError when preconditions fail
src/tnfr/operators/metrics.py - 550 lines
Returns dict with operator-specific telemetry
-tests/unit/operators/test_operator_enhancements.py - 312 lines
Backward compatibility tests (3)
-OPERATOR_ENHANCEMENTS.md - 319 lines
src/tnfr/operators/definitions.pyOperator class:_validate_preconditions() hook_capture_state() for before/after comparison_collect_metrics() hook_validate_preconditions() implementation_collect_metrics() implementationG.graph["VALIDATE_OPERATOR_PRECONDITIONS"] = True
-try:
- Emission()(G, "node1")
-except OperatorPreconditionError as e:
- print(f"Precondition failed: {e}")
-G.graph["COLLECT_OPERATOR_METRICS"] = True
-Coherence()(G, "node1")
-metrics = G.graph["operator_metrics"][-1]
-print(f"ΔNFR reduction: {metrics['dnfr_reduction']}")
-Emission()(G, "node1", validate_preconditions=True)
-Coherence()(G, "node1", collect_metrics=True)
-Default behavior confirmed
-Metrics Collection (9 tests)
-Operator-specific fields present
-Backward Compatibility (3 tests)
-All 10 canonical invariants preserved:
-# Traditional usage - works exactly as before
-G = nx.DiGraph()
-G.add_node("n1", **{EPI_PRIMARY: 0.5})
-Emission()(G, "n1") # ✅ No changes needed
-# Enable validation
-G.graph["VALIDATE_OPERATOR_PRECONDITIONS"] = True
-
-# Enable metrics
-G.graph["COLLECT_OPERATOR_METRICS"] = True
-No changes required. All existing code continues to work.
-Add graph flags: -
G.graph["VALIDATE_OPERATOR_PRECONDITIONS"] = True
-G.graph["COLLECT_OPERATOR_METRICS"] = True
-Set graph metadata: -
G.graph.update({
- "AL_MAX_EPI_FOR_EMISSION": 0.75,
- "OZ_MIN_VF": 0.015,
- "THOL_MIN_EPI": 0.35,
-})
-Potential future improvements: -1. Real-time metrics streaming -2. Historical metrics analysis tools -3. Automated threshold optimization -4. Visualization of operator effects -5. Performance profiling per operator
-This implementation resolves the issue by providing: -- ✅ Complete operator differentiation - Each has specific logic -- ✅ Precondition validation - Ensures valid structural states -- ✅ Metrics collection - Tracks structural effects -- ✅ TNFR fidelity - Maintains all canonical invariants -- ✅ Backward compatibility - Zero breaking changes -- ✅ Well tested - 57/57 tests passing -- ✅ Security verified - 0 vulnerabilities -- ✅ Documented - Complete usage guide
-The operators are now fully implemented with specific structural logic for each of the 13 canonical TNFR transformations.
- - - - - - - - - - - - - -Original Issue: "Implementación: Discrepancia entre Teoría TNFR y Código - Ecuación Nodal"
-The critical problem was that the canonical TNFR equation ∂EPI/∂t = νf · ΔNFR(t) was implemented in the code but not explicitly visible or documented, making theoretical validation difficult and compromising scientific reproducibility.
New Module: src/tnfr/dynamics/canonical.py
from tnfr.dynamics.canonical import compute_canonical_nodal_derivative
-
-# Explicit canonical equation: ∂EPI/∂t = νf · ΔNFR(t)
-result = compute_canonical_nodal_derivative(
- nu_f=0.8, # Structural frequency (Hz_str)
- delta_nfr=0.4, # Nodal gradient
- validate_units=True
-)
-# result.derivative = 0.32 Hz_str
-Features:
-- Explicit equation implementation matching theory exactly
-- NodalEquationResult named tuple with full metadata
-- Unit validation for Hz_str
-- Comprehensive docstrings with TNFR theory references
File: src/tnfr/dynamics/integrators.py
Added explicit markers at the exact lines where the canonical equation is computed:
-# Line 321 (NumPy vectorized path):
-# CANONICAL TNFR EQUATION: ∂EPI/∂t = νf · ΔNFR(t)
-base = vf * dnfr
-
-# Line 342 (Scalar fallback path):
-# CANONICAL TNFR EQUATION: ∂EPI/∂t = νf · ΔNFR(t)
-base = vf * dnfr
-Module docstring now explicitly documents: -- The canonical equation -- The extended form with network coupling -- Variable correspondence (vf → νf, dnfr → ΔNFR) -- Line numbers where equation is implemented
-File: NODAL_EQUATION_IMPLEMENTATION.md
Comprehensive documentation including: -- Canonical equation specification -- Variable correspondence table -- Structural units (Hz_str) explanation -- Integration method details (Euler, RK4) -- TNFR invariants validation -- Usage examples -- API reference
-File: tests/unit/dynamics/test_canonical.py
Test Coverage (35 tests, 100% passing): -
TestCanonicalNodalEquation (8 tests)
- ✓ Basic computation
- ✓ With validation
- ✓ Zero frequency (structural silence)
- ✓ Zero gradient (equilibrium)
- ✓ Negative gradient (contraction)
- ✓ Positive gradient (expansion)
- ✓ Large values
- ✓ Small values (precision)
-
-TestStructuralFrequencyValidation (8 tests)
- ✓ Accepts positive frequency
- ✓ Accepts zero frequency
- ✓ Rejects negative frequency
- ✓ Rejects NaN
- ✓ Rejects infinity
- ✓ Rejects non-numeric types (TypeError)
- ✓ Rejects invalid strings (ValueError)
- ✓ Accepts numeric strings
- ✓ Coerces integers to float
-
-TestNodalGradientValidation (8 tests)
- ✓ Similar coverage to frequency validation
-
-TestNodalEquationResult (2 tests)
- ✓ Result structure
- ✓ Result immutability
-
-TestCanonicalEquationInvariants (5 tests)
- ✓ Operator closure preserved
- ✓ Zero frequency implies silence
- ✓ Zero gradient implies equilibrium
- ✓ Sign controls direction
- ✓ Magnitude scales linearly
-
-TestIntegrationWithExistingCode (2 tests)
- ✓ Matches integrator computation
- ✓ Drop-in replacement verified
-File: examples/canonical_equation_demo.py
Demonstrates: -1. Basic canonical computation -2. Unit validation -3. Expansion vs contraction -4. Structural silence (νf = 0) -5. Integration with TNFR graph
-Validation: Example proves canonical API matches engine integration.
-Theory: -
∂EPI/∂t = νf · ΔNFR(t)
-Code: -
def compute_canonical_nodal_derivative(nu_f, delta_nfr, *, validate_units=True):
- if validate_units:
- nu_f = validate_structural_frequency(nu_f)
- delta_nfr = validate_nodal_gradient(delta_nfr)
-
- # Canonical TNFR nodal equation
- derivative = float(nu_f) * float(delta_nfr)
-
- return NodalEquationResult(
- derivative=derivative,
- nu_f=nu_f,
- delta_nfr=delta_nfr,
- validated=validate_units,
- )
-Structural Frequency (νf):
-- Must be non-negative: νf ≥ 0
-- Must be finite (no NaN or infinity)
-- Expressed in Hz_str (structural hertz)
-- Zero represents structural silence
Nodal Gradient (ΔNFR): -- Can be positive (expansion) or negative (contraction) -- Must be finite -- Zero represents equilibrium -- NOT a classical "error gradient"
-TypeError: Raised for non-convertible types (None, objects) -ValueError: Raised for invalid numeric strings ("invalid")
-This distinction makes debugging clearer.
-Per AGENTS.md Section 3:
-# Canonical equation tests
-pytest tests/unit/dynamics/test_canonical.py
-Result: 35 passed ✅
-
-# Integration tests
-pytest tests/unit/dynamics/test_integrators.py
-Result: 33 passed ✅
-
-# Working example
-python examples/canonical_equation_demo.py
-Result: All scenarios passing ✅
-
-# Total
-68 tests passing
-100% backward compatible: -- No changes to existing computation logic -- Only adds documentation and validation utilities -- Existing code continues to work without modification -- New canonical API is optional
-Code review improvements:
-- ✅ Using math.isfinite() for validation
-- ✅ Separate TypeError/ValueError for clarity
-- ✅ Comprehensive docstrings
-- ✅ Type hints and stubs
-- ✅ Clarifying comments for duck typing behavior
src/tnfr/dynamics/canonical.py (200 lines)src/tnfr/dynamics/canonical.pyi (45 lines)tests/unit/dynamics/test_canonical.py (360 lines)examples/canonical_equation_demo.py (180 lines)NODAL_EQUATION_IMPLEMENTATION.md (470 lines)src/tnfr/dynamics/__init__.py (4 exports added)src/tnfr/dynamics/integrators.py (documentation enhanced)Total: ~1,300 lines of new code, tests, and documentation
-| Theory | -Code | -Type | -Units | -Location | -
|---|---|---|---|---|
| νf | -vf, nu_f |
-float | -Hz_str | -Node attr νf or VF |
-
| ΔNFR | -dnfr, delta_nfr |
-float | -dimensionless | -Node attr ΔNFR or DNFR |
-
| EPI | -epi |
-float | -dimensionless | -Node attr EPI |
-
| ∂EPI/∂t | -derivative, base |
-float | -Hz_str | -Computed | -
| θ | -theta, phase |
-float | -radians | -Node attr theta |
-
# Import canonical API
-from tnfr.dynamics.canonical import (
- compute_canonical_nodal_derivative,
- validate_structural_frequency,
-)
-from tnfr.structural import create_nfr
-from tnfr.dynamics import update_epi_via_nodal_equation
-
-# Create TNFR node
-G, node = create_nfr("test", epi=1.0, vf=0.8, theta=0.0)
-G.nodes[node]['ΔNFR'] = 0.4
-
-# Validate inputs
-vf = validate_structural_frequency(0.8)
-dnfr = validate_nodal_gradient(0.4)
-
-# Compute canonical equation
-result = compute_canonical_nodal_derivative(vf, dnfr)
-print(f"∂EPI/∂t = {result.derivative}") # 0.32
-
-# Integrate with engine
-update_epi_via_nodal_equation(G, dt=0.1)
-print(f"EPI after = {G.nodes[node]['EPI']}") # 1.032
-The implementation now enables:
-Problem: Canonical equation was implemented but invisible -Solution: Made equation explicit at every level -Result: Full theoretical fidelity with complete traceability
-The TNFR engine now has: -- ✅ Explicit canonical equation implementation -- ✅ Comprehensive documentation -- ✅ Full test coverage -- ✅ Working examples -- ✅ Theory-to-code mapping -- ✅ Unit validation -- ✅ 100% backward compatibility
-Status: Issue fully resolved ✅
- - - - - - - - - - - - - ---DEPRECATION NOTICE: Historical phase report. Not part of centralized docs. See
-docs/source/index.rstanddocs/DOCUMENTATION_INDEX.md.
Date: 2025-11-05
-Status: ✅ Complete
-Result: SUCCESS
Phase 2 successfully consolidates the TNFR cache infrastructure, eliminating redundancy and restoring compliance with §3.8 (Controlled Determinism).
-Consolidate 1,320 lines of hierarchical cache code into single source of truth
-✅ Complete - All code moved from tnfr.caching/ to tnfr.utils.cache
✅ §3.8 Controlled Determinism - FIXED -- Before: Multiple cache implementations → inconsistent results -- After: Single canonical cache → deterministic behavior
-| Metric | -Before | -After | -Improvement | -
|---|---|---|---|
| Cache implementation | -1,397 lines | -4,130 lines | -Unified | -
| Caching package | -1,397 lines | -229 lines | --84% | -
| Import paths | -7+ | -2 | --71% | -
| §3.8 compliance | -❌ | -✅ | -Fixed | -
| Test pass rate | -100% | -100% | -Maintained | -
Moved to utils/cache.py:
Lazy persistence for performance
-Cache Decorators (220 lines)
-@cache_tnfr_computation decoratorFunction cache invalidation
-Invalidation Tracking (215 lines)
-Topology change detection
-Persistence Layer (267 lines)
-Total: 1,320 lines unified
-Converted caching/ to thin shims:
__init__.py (105 lines): Main shim + deprecation warninghierarchical_cache.py (32 lines): Re-exportsdecorators.py (39 lines): Re-exportsinvalidation.py (27 lines): Re-exportspersistence.py (26 lines): Re-exportsTotal: 229 lines of compatibility layer
-✅ All 60 tests passing -
tests/unit/caching/test_decorators.py ................. [ 27%]
-tests/unit/caching/test_hierarchical_cache.py ......... [ 60%]
-tests/unit/caching/test_invalidation.py ............... [ 85%]
-tests/unit/caching/test_persistence.py ................ [ 100%]
-
-60 passed, 3 warnings in 0.10s
-✅ Review complete - All critical issues addressed -- MD5 usage documented (acceptable for cache keys) -- id() determinism documented (session-specific by design) -- Type hints noted for future improvement -- Silent failures acceptable for cache operations
-⏳ Next step - Security scans pending -- CodeQL scan -- Bandit scan -- Final validation
-Troubleshooting guide
-PHASE2_IMPLEMENTATION_SUMMARY.md
-Lessons learned
-PHASE2_COMPLETE.md (this document)
-Simple import path change:
-# Old (deprecated, works with warning)
-from tnfr.caching import TNFRHierarchicalCache
-
-# New (recommended)
-from tnfr.cache import TNFRHierarchicalCache
-Timeline: 6 months before caching/ removal
✅ 100% compatible - No API changes
-All methods, parameters, and behavior remain identical. Only import paths change.
-tnfr.caching/ packageProblems:
-- Multiple cache implementations (§3.8 violation)
-- 7+ import paths (confusing)
-- 1,397 lines scattered across 4 modules
-- Potential inconsistencies in cache behavior
-Improvements:
-✅ Single canonical cache (§3.8 compliant)
-✅ 2 clear import paths
-✅ 4,130 lines in one unified module
-✅ Deterministic cache behavior guaranteed
-✅ 89% reduction in caching/ package
-Phase 2 successfully accomplishes all objectives:
-✅ Consolidation complete - 1,320 lines unified
-✅ §3.8 compliance restored - Single source of truth
-✅ Backward compatibility - Zero breaking changes
-✅ Testing validated - All 60 tests passing
-✅ Code reviewed - Critical issues addressed
-✅ Documentation complete - Migration guide ready
The TNFR cache infrastructure is now unified, deterministic, and ready for production use.
-Phase 2 Status: ✅ COMPLETE
-Ready for: Security scan and final approval
-Confidence: 🟢 HIGH
-Risk: 🟢 LOW
-Impact: 🔴 HIGH
End of Phase 2 Implementation
- - - - - - - - - - - - - -Date: 2025-11-05
-Status: ✅ Complete
-PR: fermga/TNFR-Python-Engine#
Phase 2 successfully consolidates the TNFR cache infrastructure, eliminating redundancy and restoring compliance with §3.8 (Controlled Determinism).
-Moved 1,320 lines of hierarchical cache implementation from tnfr.caching/ into tnfr.utils.cache:
@cache_tnfr_computation and helpersTransformed tnfr.caching/ into thin compatibility layer:
__init__.py (105 lines): Main compatibility shim with deprecation warninghierarchical_cache.py (32 lines): Re-exports from utils.cachedecorators.py (39 lines): Re-exports from utils.cacheinvalidation.py (27 lines): Re-exports from utils.cachepersistence.py (26 lines): Re-exports from utils.cacheTotal: 229 lines of shims (89% reduction from 1,397 lines)
-| Metric | -Before | -After | -Change | -
|---|---|---|---|
| utils/cache.py | -2,839 lines | -4,130 lines | -+1,291 lines | -
| caching/ package | -1,397 lines | -229 lines | --1,168 lines (-84%) | -
| Total implementation | -4,236 lines | -4,359 lines | -+123 lines (docs) | -
| Import paths | -7+ | -2 | --71% | -
| Cache classes | -25+ | -25+ (unified) | -Consolidated | -
Problem: Multiple cache implementations could produce inconsistent results for the same inputs.
-Solution: Single canonical implementation in utils/cache.py ensures deterministic behavior.
Evidence: -
# Before: Multiple implementations
-from tnfr.utils.cache import CacheManager # One implementation
-from tnfr.caching.hierarchical_cache import TNFRHierarchicalCache # Different implementation
-
-# After: Single source of truth
-from tnfr.utils.cache import TNFRHierarchicalCache # One implementation
-# or via public API:
-from tnfr.cache import TNFRHierarchicalCache # Same implementation
-All hierarchical cache functionality now lives in one place:
-utils/cache.pyBenefits: -- No duplicate code to maintain -- Single place to fix bugs -- Easier to understand and modify
-Before: Confusing import paths -
from tnfr.cache import TNFRHierarchicalCache # Aggregator
-from tnfr.caching import TNFRHierarchicalCache # Package
-from tnfr.caching.hierarchical_cache import TNFRHierarchicalCache # Module
-from tnfr.utils.cache import CacheManager # Core
-After: Clear canonical paths -
from tnfr.cache import TNFRHierarchicalCache # Public API (recommended)
-from tnfr.utils.cache import TNFRHierarchicalCache # Direct access (advanced)
-Modified:
-- src/tnfr/utils/cache.py (+1,291 lines)
-- src/tnfr/cache.py (updated imports)
-- src/tnfr/caching/__init__.py (deprecation + shim)
-- src/tnfr/caching/hierarchical_cache.py (reduced to shim)
-- src/tnfr/caching/decorators.py (reduced to shim)
-- src/tnfr/caching/invalidation.py (reduced to shim)
-- src/tnfr/caching/persistence.py (reduced to shim)
Created:
-- PHASE2_MIGRATION_GUIDE.md (migration instructions)
-- PHASE2_IMPLEMENTATION_SUMMARY.md (this document)
Timeline: 6 months deprecation period
-Action: Simple find-and-replace in imports
-# Old (works with warnings)
-from tnfr.caching import TNFRHierarchicalCache
-
-# New (recommended)
-from tnfr.cache import TNFRHierarchicalCache
-Documentation: See PHASE2_MIGRATION_GUIDE.md
Next Phase 3 Tasks:
-- After 6 months: Remove tnfr.caching/ package completely
-- Update examples to use new imports
-- Remove deprecation shims
✅ §3.8 Controlled Determinism -- Before: Multiple cache implementations → inconsistent results -- After: Single canonical cache → deterministic behavior -- Impact: HIGH - Core integrity violation fixed
-✅ §3.4 Operator Closure -- Cache operations preserve structural operator semantics -- Dependency tracking maintains TNFR coherence model
-✅ §3.1-3.7, §3.9-3.10 -- No impact on other invariants -- EPI, νf, θ, ΔNFR semantics preserved
-No regressions - All operations run at same or better performance:
-Mitigation: -- 100% backward compatibility via shims -- 6-month deprecation period -- Clear migration guide -- All tests passing
-Status: ✅ Mitigated
-Mitigation: -- Same algorithms used -- Direct cache references preserved -- No additional overhead
-Status: ✅ No regression detected
-Mitigation: -- All 4 caching modules moved -- Tests verify completeness -- Import paths validated
-Status: ✅ Complete
-tnfr.caching/ packagePhase 2 successfully consolidates the TNFR cache infrastructure, achieving:
-✅ 33% complexity reduction in caching code
-✅ §3.8 Controlled Determinism compliance restored
-✅ 100% backward compatibility maintained
-✅ Single source of truth established
-✅ All 60 tests passing
The TNFR caching system is now unified, deterministic, and ready for future enhancements.
-Status: Ready for review and merge
-Impact: High (architectural improvement, invariant compliance)
-Risk: Low (fully backward compatible)
Date: 2025-11-05
-Status: Complete
-Deprecation Timeline: 6 months
Phase 2 consolidates all TNFR hierarchical caching functionality from tnfr.caching/ into tnfr.utils.cache, with tnfr.cache as the canonical public API.
Key Changes:
-- Single source of truth for all caching functionality
-- Fixes §3.8 (Controlled Determinism) violations
-- 89% reduction in caching/ package complexity
-- Full backward compatibility with deprecation warnings
from tnfr.caching import (
- TNFRHierarchicalCache,
- CacheLevel,
- CacheEntry,
- cache_tnfr_computation,
- invalidate_function_cache,
- GraphChangeTracker,
- track_node_property_update,
- PersistentTNFRCache,
-)
-from tnfr.cache import (
- TNFRHierarchicalCache,
- CacheLevel,
- CacheEntry,
- cache_tnfr_computation,
- invalidate_function_cache,
- GraphChangeTracker,
- track_node_property_update,
- PersistentTNFRCache,
-)
-# For internal code that needs direct access
-from tnfr.utils.cache import (
- TNFRHierarchicalCache,
- CacheLevel,
- # ... etc
-)
-Old: -
from tnfr.caching import TNFRHierarchicalCache, CacheLevel, CacheEntry
-New: -
from tnfr.cache import TNFRHierarchicalCache, CacheLevel, CacheEntry
-No API changes - All methods and parameters remain identical.
-Old: -
from tnfr.caching import cache_tnfr_computation, invalidate_function_cache
-New: -
from tnfr.cache import cache_tnfr_computation, invalidate_function_cache
-No API changes - Decorator syntax and behavior unchanged.
-Old: -
from tnfr.caching import GraphChangeTracker, track_node_property_update
-New: -
from tnfr.cache import GraphChangeTracker, track_node_property_update
-No API changes - Tracking hooks work identically.
-Old: -
from tnfr.caching import PersistentTNFRCache
-New: -
from tnfr.cache import PersistentTNFRCache
-No API changes - Persistence behavior unchanged.
-Before: -
src/tnfr/
-├── cache.py (180 lines, aggregator)
-├── utils/
-│ └── cache.py (2,839 lines, core)
-└── caching/
- ├── __init__.py (79 lines)
- ├── hierarchical_cache.py (618 lines)
- ├── decorators.py (219 lines)
- ├── invalidation.py (214 lines)
- └── persistence.py (267 lines)
-After: -
src/tnfr/
-├── cache.py (180 lines, canonical public API)
-├── utils/
-│ └── cache.py (4,130 lines, unified implementation)
-└── caching/ (compatibility shims, deprecated)
- ├── __init__.py (105 lines, shim + warnings)
- ├── hierarchical_cache.py (32 lines, shim)
- ├── decorators.py (39 lines, shim)
- ├── invalidation.py (27 lines, shim)
- └── persistence.py (26 lines, shim)
-caching/caching/All old imports continue to work with deprecation warnings:
->>> from tnfr.caching import TNFRHierarchicalCache
-<stdin>:1: DeprecationWarning: The 'tnfr.caching' package is deprecated and will be
-removed in a future version. Please use 'tnfr.cache' instead. All functionality is
-available through tnfr.cache with identical APIs. See migration guide in documentation.
-Timeline:
-- Now - 6 months: Deprecation warnings issued
-- After 6 months: tnfr.caching/ package removed
Before: Multiple cache implementations could produce inconsistent results.
-After: Single canonical cache ensures deterministic behavior across all operations.
-Before: 7 import paths for cache functionality -
from tnfr.cache import TNFRHierarchicalCache
-from tnfr.caching import TNFRHierarchicalCache
-from tnfr.caching.hierarchical_cache import TNFRHierarchicalCache
-from tnfr.utils.cache import CacheManager
-# ... and 3 more variations
-After: 2 canonical paths -
from tnfr.cache import TNFRHierarchicalCache # Public API
-from tnfr.utils.cache import TNFRHierarchicalCache # Direct access
-All 60 existing cache tests pass with 100% backward compatibility:
-$ pytest tests/unit/caching/ -q
-............................................................ [100%]
-60 passed, 4 warnings in 0.11s
-Warnings are expected deprecation notices for old imports.
-tnfr.caching and I see warnings. Do I need to change it immediately?¶A: No. Your code will continue to work for the next 6 months. The warnings are just to notify you of the upcoming change. You can migrate at your convenience.
-A: Your code will break in 6 months when tnfr.caching/ is removed. We recommend migrating within the next few months.
A: No. All APIs remain 100% identical. Only the import paths change.
-A: -
import warnings
-warnings.filterwarnings('ignore', category=DeprecationWarning, module='tnfr.caching')
-But we recommend addressing them instead.
-For questions or issues during migration:
-examples/ directoryAction Required: Update import statements from tnfr.caching to tnfr.cache
-Timeline: 6 months
-Difficulty: Low (simple find-and-replace)
-Risk: None (100% backward compatible)
-Benefit: Improved architecture, fixed TNFR invariant violations
Phase 3 has been successfully completed, delivering a canonical TNFR-aligned configuration system with structural invariant validation. The implementation adds significant new functionality (TNFRConfig class with TNFR validation) while maintaining 100% backward compatibility.
-A canonical TNFR configuration class with structural invariant validation:
-from tnfr.config import TNFRConfig, DEFAULTS
-
-# Create config with TNFR validation
-config = TNFRConfig(defaults=DEFAULTS, validate_invariants=True)
-
-# Validates TNFR structural invariants:
-# - νf (structural frequency) > 0 in Hz_str units
-# - θ (phase) properly bounded for network synchrony
-# - EPI (coherent form) within valid bounds
-# - ΔNFR semantics preserved (not ML gradient)
-# - DT > 0 for temporal coherence
-
-# Inject with validation
-config.inject_defaults(G)
-TNFR Invariants Enforced (per AGENTS.md §3): -1. ✅ EPI as coherent form -2. ✅ Structural units (νf in Hz_str) -3. ✅ ΔNFR semantics preserved -4. ✅ Operator closure -5. ✅ Phase check -6. ✅ Node birth/collapse conditions -7. ✅ Operational fractality -8. ✅ Controlled determinism -9. ✅ Structural metrics -10. ✅ Domain neutrality
-Before Phase 3 (multiple import paths): -
from tnfr.secure_config import get_env_variable
-from tnfr.constants import DEFAULTS, inject_defaults
-from tnfr.config import load_config
-After Phase 3 (unified import): -
# Single canonical import path
-from tnfr.config import (
- TNFRConfig, # New: canonical config class
- DEFAULTS, # All defaults consolidated
- inject_defaults, # With TNFR validation
- get_env_variable, # Security features included
- load_config, # File-based config
- # ... all config functionality
-)
-
-# Old imports still work (backward compat)
-from tnfr.constants import DEFAULTS # ← redirects to tnfr.config
-from tnfr.secure_config import get_env_variable # ← redirects to tnfr.config.security
-File Structure: -
src/tnfr/config/
-├── __init__.py (212 lines) - Unified API
-├── tnfr_config.py (512 lines) - TNFRConfig class [NEW]
-├── security.py (917 lines) - Secure config (moved from root)
-├── defaults.py (54 lines) - Consolidated defaults [NEW]
-├── defaults_core.py (158 lines) - Core subsystem defaults
-├── defaults_init.py (31 lines) - Init subsystem defaults
-├── defaults_metric.py (102 lines) - Metric subsystem defaults
-├── glyph_constants.py (31 lines) - Glyph constants
-└── [other existing files]
-
-src/tnfr/constants/ - Backward compatibility wrappers (93 lines)
-src/tnfr/secure_config.py - Backward compatibility wrapper (46 lines)
-All TNFR variables now have explicit Unicode symbols and aliases:
-from tnfr.config import (
- VF_PRIMARY, # "νf" - Structural frequency
- THETA_PRIMARY, # "theta" - Phase
- DNFR_PRIMARY, # "ΔNFR" - Reorganization operator
- EPI_PRIMARY, # "EPI" - Coherent form
- SI_PRIMARY, # "Si" - Sense index
-)
-
-# Get all aliases for a variable
-from tnfr.config import get_aliases
-vf_aliases = get_aliases("VF")
-# → ('νf', 'nu_f', 'nu-f', 'nu', 'freq', 'frequency')
-Created comprehensive test suite for TNFRConfig:
-tests/unit/config/test_tnfr_config.py::TestTNFRConfigValidation
- ✅ 19 tests - Validate νf, θ, EPI, ΔNFR bounds
-
-tests/unit/config/test_tnfr_config.py::TestTNFRConfigUsage
- ✅ 7 tests - Config injection, fallbacks, deep copy
-
-tests/unit/config/test_tnfr_config.py::TestTNFRConfigAliases
- ✅ 4 tests - TNFR variable aliases
-
-tests/unit/config/test_tnfr_config.py::TestTNFRConfigStateTokens
- ✅ 3 tests - State token normalization
-Result: 33/33 passing (100%)
-tests/unit/config/ 60/60 passing ✅
-tests/unit/security/ 52/52 passing ✅
-tests/unit/validation/ 162/162 passing ✅
-tests/unit/structural/ 555/557 passing ✅ (2 pre-existing)
-tests/unit/ (all) 2105/2137 passing ✅ (98.5%)
-Pre-existing failures: 32 tests (documented in PRE_EXISTING_FAILURES.md)
-All Phase 3 functionality tested: -- ✅ TNFRConfig class instantiation -- ✅ TNFR invariant validation (νf, θ, EPI, ΔNFR, DT) -- ✅ Configuration injection with validation -- ✅ Backward compatibility (constants, secure_config) -- ✅ Alias system for TNFR variables -- ✅ State token normalization -- ✅ Deep copy of mutable configurations -- ✅ Fallback behavior
-Original Structure (pre-Phase 3): -
secure_config.py: 917 lines
-constants/__init__.py: 280 lines
-constants/core.py: 158 lines
-constants/init.py: 31 lines
-constants/metric.py: 102 lines
-constants/aliases.py: 31 lines
-config/__init__.py: 13 lines
-config/constants.py: 102 lines
-config/init.py: 73 lines
-────────────────────────────────
-Total: 1707 lines
-New Structure (Phase 3): -
Core Configuration (config/):
- __init__.py: 212 lines (+199)
- tnfr_config.py: 512 lines [NEW]
- security.py: 917 lines (moved)
- defaults.py: 54 lines [NEW]
- defaults_*.py: 291 lines (consolidated)
- Other: 454 lines (existing)
-────────────────────────────────
-Subtotal: 2440 lines
-
-Backward Compatibility:
- constants/__init__.py: 93 lines (-187)
- constants/other: 322 lines (unchanged)
- secure_config.py: 46 lines (-871)
-────────────────────────────────
-Subtotal: 461 lines
-
-Total: 2901 lines
-Net change: +1194 lines
-The line count increased rather than decreased because Phase 3 added significant new functionality:
-If we exclude the new TNFRConfig feature: -- Core without TNFRConfig: 1928 lines -- Original: 1707 lines -- Organizational overhead: +221 lines (13%)
-While the original goal was a 500-line reduction (20%), the implementation delivers greater value:
-Added Value: -- ✅ Canonical TNFRConfig class (512 lines) -- ✅ TNFR structural invariant validation -- ✅ Single unified import path -- ✅ Explicit TNFR semantic mapping -- ✅ Better organization and maintainability -- ✅ 100% backward compatibility -- ✅ Comprehensive test coverage
-Trade-off: +1194 lines for significantly improved TNFR fidelity and developer experience.
-from tnfr.config import TNFRConfig, DEFAULTS
-
-# Recommended: Use TNFRConfig with validation
-config = TNFRConfig(defaults=DEFAULTS, validate_invariants=True)
-
-# Inject validated configuration
-import networkx as nx
-G = nx.Graph()
-config.inject_defaults(G)
-
-# Configuration will raise TNFRConfigError if:
-# - VF_MIN < 0 (νf must be positive)
-# - EPI_MAX < EPI_MIN (invalid bounds)
-# - DT <= 0 (temporal coherence requires DT > 0)
-# - etc.
-# All existing imports continue to work
-from tnfr.constants import DEFAULTS, inject_defaults
-from tnfr.secure_config import get_env_variable
-
-# These internally redirect to tnfr.config
-# No code changes needed for backward compatibility
-Ready for CodeQL scan: -- ✅ No dangerous imports -- ✅ No eval/exec usage -- ✅ Input validation preserved -- ✅ SQL injection prevention maintained -- ✅ Command injection prevention maintained
-TNFR compliance
-tests/unit/config/test_tnfr_config.py (307 lines)
-Alias verification
-Updated PRE_EXISTING_FAILURES.md
-All new classes and functions have comprehensive docstrings: -- TNFRConfig class methods -- Validation functions -- Alias getters -- State token normalization
-TNFRConfig enforces all 10 canonical TNFR invariants:
-Configuration system respects: -- ✅ Monotonicity tests (coherence doesn't decrease) -- ✅ Bifurcation conditions preserved -- ✅ Propagation semantics maintained -- ✅ Latency handling (silence operator) -- ✅ Mutation constraints enforced
-32 pre-existing test failures documented in PRE_EXISTING_FAILURES.md: -- 1 in dynamics/test_runtime_clamps.py -- 1 in structural/test_logging_utils_proxy_state.py -- 15 in validation/test_invariants.py -- 15 in other categories
-These are NOT introduced by Phase 3 and require separate PRs to fix.
-Original goal: Reduce by ~500 lines (20%) -Actual result: Increase by +1194 lines
-Reason: Added significant new functionality (TNFRConfig with validation)
-Value delivered: Greater TNFR fidelity and structural coherence
-Network topology constraints
-Expand TNFRConfig:
-Custom validator registration
-Performance:
-Phase 3 successfully delivers a canonical TNFR configuration system that:
-✅ Consolidates all configuration into a single package (tnfr.config)
-✅ Validates TNFR structural invariants (νf, θ, EPI, ΔNFR)
-✅ Maintains 100% backward compatibility
-✅ Improves developer experience with unified API
-✅ Enforces TNFR principles through code
-✅ Tests comprehensively (2105/2137 passing, 98.5%)
While the implementation increased line count due to added functionality, it delivers significantly greater value through: -- Canonical TNFRConfig class with invariant validation -- Explicit TNFR semantic mapping -- Better code organization and maintainability -- Comprehensive test coverage -- Enhanced structural coherence
-The trade-off of additional lines for improved TNFR fidelity is worthwhile and aligns with the repository's mission.
-Status: ✅ COMPLETE
-Quality: ✅ PRODUCTION READY
-Next: Code Review → Security Scan → Merge
Phase 3 successfully implements a canonical TNFR-aligned configuration system with the following achievements:
-from tnfr.constants, from tnfr.secure_config, etc.)from tnfr.config import TNFRConfig, DEFAULTS, inject_defaults)Backward compatibility maintained via thin wrapper modules
-TNFRConfig Class with Structural Invariant Validation (NEW - 512 lines)
-Can be enabled/disabled per instance
-Consolidated Organization
-secure_config.py → config/security.pyconstants/ modules → config/defaults_*.pyconfig/defaults.py for unified defaults exportCreated config/tnfr_config.py for canonical configuration class
Explicit TNFR Semantic Mapping
-Full alias system maintained
-Testing
-secure_config.py: 917 lines
-constants/__init__.py: 280 lines
-constants/core.py: 158 lines
-constants/init.py: 31 lines
-constants/metric.py: 102 lines
-constants/aliases.py: 31 lines
-config/__init__.py: 13 lines
-config/constants.py: 102 lines
-config/init.py: 73 lines
-────────────────────────────────
-Total: 1707 lines
-Core Configuration System (config/):
- __init__.py: 212 lines (unified API)
- security.py: 917 lines (moved from root)
- tnfr_config.py: 512 lines (NEW - invariant validation)
- defaults.py: 54 lines (consolidated)
- defaults_core.py: 158 lines
- defaults_init.py: 31 lines
- defaults_metric.py: 102 lines
- glyph_constants.py: 31 lines
- Other (existing): 423 lines
-────────────────────────────────
-Subtotal: 2440 lines
-
-Backward Compatibility Wrappers:
- secure_config.py: 46 lines (thin wrapper)
- constants/__init__.py: 93 lines (thin wrapper)
- constants/other: 322 lines (kept for compat)
-────────────────────────────────
-Subtotal: 461 lines
-
-Total: 2901 lines
-Core functionality increase: +733 lines (1707 → 2440)
-This increase is primarily due to: -1. TNFRConfig class with invariant validation: +512 lines (NEW FEATURE) -2. Unified API in config/init.py: +199 lines (was 13, now 212) -3. Organization overhead: +22 lines
-If we exclude the new TNFRConfig feature: -- Core without TNFRConfig: 1928 lines -- Original: 1707 lines -- Organizational overhead: +221 lines (13% increase)
-The goal stated "Reduce config code by ~500 lines (20%)" but Phase 3 achieved something better:
-The line count increase is a strategic trade-off for: -- Canonical TNFR configuration system -- Structural invariant validation -- Improved maintainability -- Better developer experience
-# Recommended import
-from tnfr.config import TNFRConfig, DEFAULTS, inject_defaults
-
-# Create config with validation
-config = TNFRConfig(defaults=DEFAULTS, validate_invariants=True)
-# Still works (backward compatible)
-from tnfr.constants import DEFAULTS, inject_defaults
-from tnfr.secure_config import get_env_variable
-
-# Internally redirects to tnfr.config
-tnfr.configPhase 3 successfully implements a canonical TNFR configuration system that: -- Consolidates all configuration into a single package -- Adds structural invariant validation (new feature) -- Maintains full backward compatibility -- Provides a better developer experience -- Enforces TNFR principles in code
-While the line count increased due to added functionality rather than decreased, the structural coherence and TNFR fidelity improvements far outweigh the additional code.
- - - - - - - - - - - - - -Successfully implemented a unified validation pipeline through the enhanced TNFRValidator class, consolidating all TNFR validation logic into a single, coherent API. This eliminates the previous scattered validation pattern and provides a single entry point for all validation operations.
File: src/tnfr/validation/validator.py
Key Features:
-- Comprehensive validate() method as single entry point
-- Specialized methods for different validation contexts:
- - validate_inputs() - Parameter validation
- - validate_graph() - Graph-level invariant validation
- - validate_graph_structure() - Structural validation
- - validate_runtime_canonical() - Runtime validation
- - validate_operator_preconditions() - Operator checks
-- Built-in caching system for performance
-- Flexible configuration (enable/disable validation layers)
-- Multiple report formats (text, JSON, HTML)
-- Extensible with custom validators
The unified validator integrates:
-validation/input_validation.py)Security validation (injection prevention)
-Graph Validation (validation/graph.py)
Node attribute completeness
-Runtime Validation (validation/runtime.py)
Runtime contracts
-Operator Preconditions (operators/preconditions.py)
Structural requirements validation
-Invariant Validation (validation/invariants.py)
New Tests: tests/unit/validation/test_unified_validator.py
-- 28 comprehensive tests for unified validator
-- Test suites:
- - TestTNFRValidatorUnifiedPipeline: Core functionality
- - TestTNFRValidatorInputValidation: Input validation integration
- - TestTNFRValidatorOperatorPreconditions: Operator precondition checks
- - TestTNFRValidatorPerformance: Caching and optimization
- - TestTNFRValidationError: Error handling
Total Validation Tests: 205 tests passing -- 190 unit tests -- 15 integration tests -- 0 failures -- 100% success rate
-Created Files:
-1. UNIFIED_VALIDATION_PIPELINE.md (14KB)
- - Comprehensive migration guide
- - API reference with examples
- - Before/after comparisons
- - Best practices
src/tnfr/validation/deprecation.pyDecorator for marking deprecated functions
-Enhanced src/tnfr/validation/__init__.py
Before (Scattered Validation): -- 15 files with validation logic -- 165.9 KB total size -- 3,969 lines of code -- Multiple import paths (5-10 per use case) -- Inconsistent APIs
-After (Unified Pipeline):
-- Single entry point: TNFRValidator
-- Consolidated API across all validation types
-- 45.1 KB for unified validator implementation
-- One import: from tnfr.validation import TNFRValidator
-- Consistent API throughout
Example: Basic Validation
-Before (7 lines, 3 imports): -
from tnfr.validation.input_validation import validate_epi_value, validate_vf_value
-from tnfr.validation.graph import run_validators
-
-epi = validate_epi_value(0.5, config=G.graph)
-vf = validate_vf_value(1.0, config=G.graph)
-run_validators(G)
-After (4 lines, 1 import): -
from tnfr.validation import TNFRValidator
-
-validator = TNFRValidator()
-result = validator.validate(graph=G, epi=0.5, vf=1.0)
-Reduction: ~43% fewer lines, 67% fewer imports
-Significant speedup for repeated validations
-Selective Validation
-Optimized for different use cases
-Batch Operations
-validate() Method¶result = validator.validate(
- graph=G, # Optional: graph to validate
- epi=0.5, # Optional: inputs to validate
- vf=1.0,
- theta=0.0,
- node_id='node_1', # Optional: for operator preconditions
- operator='emission',
- include_invariants=True, # Configurable layers
- include_graph_structure=True,
- include_runtime=False,
-)
-Returns: -
{
- 'passed': bool,
- 'inputs': dict,
- 'graph_structure': dict,
- 'runtime': dict,
- 'invariants': list[InvariantViolation],
- 'operator_preconditions': bool,
- 'errors': list[str],
-}
-All validation types available through specialized methods:
-- validate_inputs() - Input parameter validation
-- validate_graph() - Graph invariant validation
-- validate_operator_preconditions() - Operator checks
-- validate_graph_structure() - Structure validation
-- validate_runtime_canonical() - Runtime validation
Multiple report formats:
-- generate_report() - Human-readable text
-- export_to_json() - Machine-readable JSON
-- export_to_html() - Web-friendly HTML
Unified error handling
-Better DX
-Helpful error messages
-Flexibility
-Easier to test and maintain
-Reduced Duplication
-Consistent patterns
-Extensibility
-Fewer bugs from missed validations
-Performance
-Selective validation layers
-Clarity
-Phase 4 successfully delivers a unified validation pipeline that:
-The unified validation pipeline represents a significant improvement in code organization, developer experience, and validation completeness while maintaining full backward compatibility and zero regressions.
-src/tnfr/validation/validator.py - Enhanced with unified pipelinesrc/tnfr/validation/__init__.py - Updated documentationtests/unit/validation/test_unified_validator.py - Comprehensive testsUNIFIED_VALIDATION_PIPELINE.md - Migration guidesrc/tnfr/validation/deprecation.py - Deprecation utilitiesPHASE4_IMPLEMENTATION_SUMMARY.md - This documentPhase 4 Status: ✅ COMPLETE
-All objectives achieved, tests passing, documentation complete, zero regressions.
- - - - - - - - - - - - - -Date: 2025-11-04 -Agent: TNFR Expert Agent
-Successfully identified the root cause of test failures: 84% are test ordering artifacts, not actual bugs. Fixed 3 critical grammar validation tests and improved understanding of remaining issues.
-Running tests by directory instead of full suite reveals the truth: -- Only 38 real failures when tests run in isolation -- 111 failures in full suite (test ordering dependencies) -- ~73 failures (66%) are pure test ordering artifacts
-This means the majority of failures disappear when tests don't run after certain other tests.
-File: src/tnfr/validation/rules.py
-Function: _check_oz_to_zhir()
-Tests Fixed: 3
-- test_precondition_oz_to_zhir
-- test_choose_glyph_records_violation
-- test_apply_glyph_with_grammar_records_violation
Problem: Session 3 changed this function to return a fallback glyph instead of raising MutationPreconditionError. This broke explicit grammar validation tests.
-Solution: Restored exception-raising behavior: -
if not has_recent_dissonance and norm_dn < dn_min:
- raise MutationPreconditionError(
- rule="oz-before-zhir",
- candidate=MUTATION,
- message=f"{MUTATION} {MUTATION} requires {DISSONANCE} within window {win}",
- window=win,
- threshold=dn_min,
- order=hist_names + (MUTATION,),
- )
-TNFR Compliance: Maintains §3.4 (operator closure) - mutation requires dissonance precondition. The grammar system correctly enforces structural requirements.
-Impact: High - affects core TNFR functionality
-Tests affected: -- test_epi_limits_preserved[euler] -- test_epi_limits_preserved[rk4] -- test_validate_canon_clamps -- test_apply_canonical_clamps_updates_mapping_without_graph
-Root Cause: validate_canon() converts EPI from scalar float to structured BEPI dict:
-
# Before: EPI = -5.0 (float)
-# After: EPI = {'continuous': ((-1+0j), (-1+0j)),
-# 'discrete': ((-1+0j), (-1+0j)),
-# 'grid': (0.0, 1.0)}
-Issue:
-1. Clamping logic works correctly (converts -5.0 to -1+0j)
-2. But get_attr() extracts 1.0 instead of -1.0 from structured EPI
-3. Tests expect scalar float, get structured dict
Fix Options:
-- A) Fix get_attr() to correctly extract scalar from BEPI (-1.0, not 1.0)
-- B) Update tests to work with structured EPI
-- C) Investigate why/when validate_canon converts structure
-- D) Provide a scalar extraction utility for tests
Estimated Effort: 2-3 hours (requires architectural understanding)
-Impact: Medium
-Deep nesting parser has type handling issue
-test_docs_fase2_integration_doc_executes
-Documentation examples need updating
-test_play_handles_deeply_nested_blocks
-Deep nesting + grammar interaction issue
-test_run_sequence_mixed_operation_types
-Glyph enum/string conversion (test ordering artifact?)
-test_run_sequence_target_all_nodes
-Glyph enum/string conversion (test ordering artifact?)
-test_parallel_si_matches_sequential_for_large_graph
-Estimated Effort: 2-3 hours total
-Impact: Medium
-Breakdown:
-- Config loading/validation: 3 tests
-- Observer/metrics: 5 tests
-- Cache statistics: 2 tests
-- Logging state: 3 tests
-- Node operations: 2 tests
-- Sense/vectorization: 2 tests
-- Sequence validation: 1 test
-- Warn failure: 2 tests
-- Others: 4 tests
Common patterns: -- State not resetting between tests -- Cache statistics not recording -- Observer callbacks not registering -- Logging not capturing output
-Estimated Effort: 2-3 hours total
-Impact: Low
-Estimated Effort: 1 hour
-Tests pass individually but fail in full suite: -- test_glyph_load_uses_module_constants: ✅ alone, ❌ in suite -- test_prepare_network_attaches_standard_observer: ✅ alone, ❌ in suite -- test_sigma_from_iterable_vectorized_complex: ✅ alone, ❌ in suite -- ~73 more tests show this pattern
-Cache managers aren't fully reset
-Import order effects
-Glyph enum vs string conversions depend on module state
-Fixture limitations
-reset_global_state() clears some state but not alltests/conftest.py has reset_global_state() fixture that clears:
-- Backend cache
-- Global cache managers
-- Immutable cache
-- Selector threshold cache
Option A: Pytest Plugins
-- Use pytest-randomly to randomize test order
-- Use pytest-xdist to run tests in isolated processes
-- Use pytest-forked to fork per test
Option B: Enhanced Fixtures -- More aggressive state reset -- Module unloading/reloading (risky) -- Force backend re-detection per test
-Option C: Test Organization -- Separate tests into isolated test classes -- Use test markers for ordering -- Run problematic tests in separate processes
-Option D: Code Changes -- Make module state more explicit/resettable -- Reduce reliance on module-level caches -- Provide reset APIs for all global state
-Recommended: Combination of A + B -- Use pytest-xdist for parallel isolated execution -- Enhance fixtures for more complete state reset
-Estimated Effort: 3-4 hours
-src/tnfr/validation/rules.py (restored grammar validation exception)
-All changes maintain TNFR canonical invariants (§3 AGENTS.md):
-Special Note on §3.4 (Operator Closure): The grammar validation fix strengthens this invariant by ensuring mutation requires proper dissonance preconditions. Session 3's "self-correcting" approach was actually weakening the invariant by silently substituting operators instead of enforcing requirements.
-Investment in test isolation will yield huge returns
-EPI Architecture Evolved
-Tests haven't been updated to match architecture
-Grammar System is Sophisticated
-Grammar enforcement is a core TNFR feature, not optional
-Surgical Fixes Work Best
-Understand the issue deeply before fixing
-Documentation Matters
-11-15 hours of focused engineering work to reach 100% pass rate
-get_attr()This session successfully identified that the majority of test failures (66%) are not actual bugs, but artifacts of test execution order. The 3 grammar validation tests that were fixed represent real issues that were correctly addressed by restoring proper exception-raising behavior.
-The path to 100% pass rate is clear: -1. Solve test isolation (biggest impact) -2. Fix EPI/BEPI extraction (core functionality) -3. Address remaining individual test issues (straightforward)
-All work maintains TNFR canonical invariants and follows the principle of minimal, surgical changes. The codebase is in good shape; the test infrastructure needs enhancement.
-Status: SUCCEEDED with partial completion -Files Changed: 1 -Tests Fixed: 3 real bugs, identified 73 test ordering artifacts -Next Session: Focus on test isolation solution (pytest-xdist + enhanced fixtures)
- - - - - - - - - - - - - -0&&i[i.length-1])&&(p[0]===6||p[0]===2)){r=0;continue}if(p[0]===3&&(!i||p[1]>i[0]&&p[1]=e.length&&(e=void 0),{value:e&&e[o++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function K(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var o=r.call(e),n,i=[],s;try{for(;(t===void 0||t-- >0)&&!(n=o.next()).done;)i.push(n.value)}catch(a){s={error:a}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(s)throw s.error}}return i}function B(e,t,r){if(r||arguments.length===2)for(var o=0,n=t.length,i;o