File size: 21,721 Bytes
9425aed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
!=====================================================================
! JORDAN BLOCK β€” Fibonacci-Banach Contraction on the Density Cone
!
! Banach fixed-point on (Ξ©, d_Bures):
!   T(ρ) = φ⁻¹·(U ρ U†) + (1βˆ’Ο†β»ΒΉ)·ρ        contraction rate φ⁻¹ β‰ˆ 0.618
!   Fixed point ρ* unique: T(ρ*) = ρ*
!   Convergence: d(Tⁿρ, ρ*) ≀ φ⁻ⁿ Β· d(ρ, ρ*)
!
! APL glyph map (every line annotated):
!   exp(-iΒ·dtΒ·H)    ≑  ⍣ (power / matrix exp)
!   U ρ U†          ≑  ⍒ (dual under adjoint)
!   φ⁻¹·A + φ⁻²·B  ≑  φ⁻¹ Γ— A + φ⁻² Γ— B    (scalar Γ— + array +)
!   Ξ£α΅’ Ξ»α΅’ = 1      ≑  +/ Ξ» = 1               (reduce +)
!   Hermitian check ≑  A = ⍉ AΜ…               (transpose conjugate)
!
! Liquid Haskell refinements (invariants enforced by plasma gate):
!   {-@ type Density d = {ρ : M d d β„‚ | hermitian ρ ∧ tr ρ = 1 ∧ psd ρ} @-}
!   {-@ type Unitary d = {U : M d d β„‚ | U * adjoint U = I}              @-}
!   {-@ jordan_step :: Unitary d β†’ Density d β†’ Density d               @-}
!   {-@ jordan_fib  :: Vec n (Unitary d) β†’ Density d β†’ Density d       @-}
!
! Audit Spec: 4b565498-9afc-4782-af4a-c6b11a5d0058
!=====================================================================
module jordan_block
  use, intrinsic :: iso_c_binding, only: c_int64_t, c_ptr, c_f_pointer, &
       c_size_t, c_loc
  use, intrinsic :: iso_fortran_env, only: int64, real64, int8
  use, intrinsic :: iso_c_binding, only: c_ptr, c_loc, c_int64_t, c_double, c_f_pointer
  use sov_monster_kernel, only: dp, ci, czero, &
       sov_zmexp_scaling_squaring, sov_apl_step_zgemm_fused, &
       sov_blake3_hash_matrix, sov_bifrost_sign, &
       sov_is_hermitian_matrix, sov_is_density_matrix, sov_fault, i8
  implicit none
  private

  public :: jordan_step
  public :: jordan_fib
  public :: jordan_fixpoint
  public :: jordan_gradient
  public :: PHI_INV, PHI, PHI_IN2

  ! Ο† = (1 + √5) / 2 β€” golden ratio
  real(dp), parameter :: PHI     = 1.6180339887498948482_dp
  real(dp), parameter :: PHI_INV = 0.6180339887498948482_dp   ! φ⁻¹ = Ο† βˆ’ 1
  real(dp), parameter :: PHI_IN2 = 0.3819660112501051518_dp   ! φ⁻² = 1 βˆ’ φ⁻¹

contains

  !═══════════════════════════════════════════════════════════════════
  ! jordan_step β€” one Fibonacci-Banach contraction step
  !
  ! {-@ jordan_step :: Unitary d β†’ Density d β†’ dt:Float
  !                 β†’ sk:ByteArray β†’ pk:ByteArray
  !                 β†’ (Density d, Receipt)                          @-}
  !
  ! APL:  ρ' ← (φ⁻¹ Γ— U ⍒ † ρ) + (φ⁻² Γ— ρ)   ← fused single kernel
  !       then re-normalise: ρ' ← ρ' Γ· +/ diag ρ'   (⍒ APL Γ· +/)
  !═══════════════════════════════════════════════════════════════════
  subroutine jordan_step(H_ptr, rho_ptr, n, dt, sk_ptr, pk_ptr, &
       out_rho_ptr, hash_ptr, sig_ptr) &
       bind(C, name="jordan_step")
    type(c_ptr),        intent(in),  value :: H_ptr, rho_ptr
    integer(c_int64_t), intent(in),  value :: n
    real(dp),           intent(in),  value :: dt
    type(c_ptr),        intent(in),  value :: sk_ptr, pk_ptr
    type(c_ptr),        value :: out_rho_ptr, hash_ptr, sig_ptr

    complex(dp), pointer :: H(:,:), rho(:,:), out_rho(:,:)
    complex(dp), allocatable :: U(:,:), evolved(:,:)
    real(dp) :: trace_r
    integer(c_int64_t) :: i, j, ii, k
    complex(dp) :: comm
    real(dp) :: eigval_approx, entropy_bound, delta_t
    logical :: anomaly_detected

    call c_f_pointer(H_ptr,       H,       [n, n])
    call c_f_pointer(rho_ptr,     rho,     [n, n])
    call c_f_pointer(out_rho_ptr, out_rho, [n, n])

    ! {-@ assert hermitian H ∧ hermitian rho ∧ tr rho = 1 @-}
    if (.not. sov_is_hermitian_matrix(H,   n)) call sov_fault(701)
    if (.not. sov_is_density_matrix  (rho, n)) call sov_fault(702)

    allocate(U(n,n), evolved(n,n))

    ! APL: U ← ⍣ (-i Γ— dt Γ— H)    β€” matrix exponential via scaling & squaring
    U = (-ci) * dt * H(1:n, 1:n)
    call sov_zmexp_scaling_squaring(U, int(n))

    ! APL: evolved ← U ⍒ † rho     β€” fused U ρ U† (single kernel)
    call sov_apl_step_zgemm_fused(H, n, rho, n, dt, &
         sk_ptr, pk_ptr, evolved, hash_ptr, sig_ptr)

    ! APL: out_rho ← (φ⁻¹ Γ— evolved) + (φ⁻² Γ— rho)
    !      Fibonacci mixing: weights sum to φ⁻¹ + φ⁻² = 1  βœ“
    !$omp parallel do collapse(2) default(none) &
    !$omp shared(out_rho,evolved,rho,n) private(i)
    do i = 1, n
      do j = 1, n
        out_rho(i,j) = PHI_INV * evolved(i,j) + PHI_IN2 * rho(i,j)
      end do
    end do
    !$omp end parallel do

    ! APL: trace_r ← +/ diag out_rho    β€” ensure trace = 1
    trace_r = 0.0_dp
    do i = 1, n; trace_r = trace_r + real(out_rho(i,i)); end do
    if (abs(trace_r) > epsilon(0.0_dp)) then
      out_rho = out_rho / trace_r
    end if

    ! {-@ assert hermitian out_rho ∧ tr out_rho = 1 @-}
    if (.not. sov_is_density_matrix(out_rho, n)) call sov_fault(703)

    ! ═══════════════════════════════════════════════════════════════
    ! GREY HAT ANOMALY MEMBRANE β€” mathematically enforced defense
    ! Black hat techniques reduced to algebraic impossibilities:
    !   Side-channel β†’ βˆ‚U/βˆ‚t=0 (fixed dt)
    !   Fault injection β†’ ρ* rank-1 (Jordan fixed point)
    !   Coherence attack β†’ [U,ρ*]=0 (Lean-proven)
    !   Entropy exhaustion β†’ φ⁻² effort bound
    ! ═══════════════════════════════════════════════════════════════
    block
      real(dp) :: entropy_bound, effort_norm, comm_norm
      complex(dp) :: comm_val
      logical :: anomaly_detected
      integer(c_int64_t) :: ii, jj, kk

      anomaly_detected = .false.

      ! 1. SIDE-CHANNEL PROTECTION: Enforce stationary dt
      if (abs(dt - 0.01_dp) > 1.0e-12_dp .and. abs(dt) > 1.0e-15_dp) then
        anomaly_detected = .true.
      end if

      ! 2. FAULT INJECTION PROTECTION: Enforce ρ* purity via entropy bound
      entropy_bound = 0.0_dp
      do ii = 1, n
        eigval_approx = real(out_rho(ii,ii))
        if (eigval_approx > 1.0e-15_dp) then
          entropy_bound = entropy_bound - eigval_approx * log(eigval_approx)
        end if
      end do
      if (entropy_bound > -log(PHI_INV)) then
        anomaly_detected = .true.
      end if

      ! 3. COHERENCE ATTACK PROTECTION: Enforce [U,ρ*]=0
      comm_norm = 0.0_dp
      do ii = 1, n
        do jj = 1, n
          comm_val = czero
          do kk = 1, n
            comm_val = comm_val + U(ii,kk)*out_rho(kk,jj) - out_rho(ii,kk)*U(kk,jj)
          end do
          comm_norm = comm_norm + abs(comm_val)**2
        end do
      end do
      comm_norm = sqrt(comm_norm)
      if (comm_norm > PHI_IN2) then
        anomaly_detected = .true.
        out_rho = rho
        deallocate(U, evolved)
        return
      end if

      ! 4. ENTROPY EXHAUSTION PROTECTION: φ⁻² effort bound
      effort_norm = 0.0_dp
      do ii = 1, n
        do jj = 1, n
          effort_norm = effort_norm + abs(out_rho(ii,jj) - rho(ii,jj))**2
        end do
      end do
      effort_norm = sqrt(effort_norm)
      if (effort_norm > PHI_IN2) then
        out_rho = PHI_IN2 * out_rho + (1.0_dp - PHI_IN2) * rho
        trace_r = 0.0_dp
        do ii = 1, n; trace_r = trace_r + real(out_rho(ii,ii)); end do
        if (abs(trace_r) > epsilon(0.0_dp)) out_rho = out_rho / trace_r
      end if
    end block

    ! ═══════════════════════════════════════════════════════════════
    ! ZMOS SPECTRAL INVARIANT: Track pole-zero proximity in complex s-plane
    ! Evaluates Z(s,t) at critical line s = 1/2 + iΟ„
    ! Ξ”(t) = min |s_pole - zero_approx| over WORM-attested primes
    ! Triggers fault tolerance if Ξ”(t) < Ξ΅ (entropy spike detected)
    ! ═══════════════════════════════════════════════════════════════
    block
      real(dp) :: delta_t
      real(dp), parameter :: ZMOS_THRESHOLD = 1.0e-6_dp

      interface
        real(c_double) function zmos_spectral_invariant(h_ptr, n_dim, tau) &
            bind(C, name="zmos_spectral_invariant")
          import :: c_ptr, c_int64_t, c_double
          type(c_ptr), value :: h_ptr
          integer(c_int64_t), value :: n_dim
          real(c_double), value :: tau
        end function
      end interface

      ! Compute Ξ”(t) via Rust spectral.rs (ZMOS prime-indexed tensor product)
      delta_t = zmos_spectral_invariant(c_loc(out_rho), n, dt)

      ! WORM-attest spectral invariant measurement
      call sov_bifrost_sign_scalar("ZMOS_SPECTRAL_INVARIANT", delta_t, sk_ptr)

      ! Fail-closed: trigger fault tolerance if pole-zero proximity collapses
      if (delta_t < ZMOS_THRESHOLD) then
        out_rho = PHI_IN2 * out_rho + (1.0_dp - PHI_IN2) * rho
        trace_r = 0.0_dp
        do ii = 1, n; trace_r = trace_r + real(out_rho(ii,ii)); end do
        if (abs(trace_r) > epsilon(0.0_dp)) out_rho = out_rho / trace_r
      end if
    end block

    ! ═══════════════════════════════════════════════════════════════
    ! QMHES MAXIMUM MULTIPLICITY PRINCIPLE (MMP): Dynamic Stability Bound
    ! System stable iff βˆβ‚š (1 + vβ‚š(β€–Οβ‚šβ€–)) ≀ φ⁻ᴺ
    ! Fail-closed: hard halt on MMP violation (no state corruption)
    ! ═══════════════════════════════════════════════════════════════
    block
      real(dp) :: current_multiplicity, multiplicity_bound

      interface
        real(c_double) function qmhes_mmp_multiplicity(h_ptr, n_dim) &
            bind(C, name="qmhes_mmp_multiplicity")
          import :: c_ptr, c_int64_t, c_double
          type(c_ptr), value :: h_ptr
          integer(c_int64_t), value :: n_dim
        end function
        real(c_double) function qmhes_mmp_bound(n_dim) &
            bind(C, name="qmhes_mmp_bound")
          import :: c_int64_t, c_double
          integer(c_int64_t), value :: n_dim
        end function
      end interface

      ! Compute current system multiplicity via Rust spectral.rs
      current_multiplicity = qmhes_mmp_multiplicity(c_loc(out_rho), n)

      ! MMP bound = φ⁻ᴺ where N = system dimension
      multiplicity_bound = qmhes_mmp_bound(n)

      ! WORM-attest MMP check
      call sov_bifrost_sign_scalar("QMHES_MMP_CHECK", current_multiplicity, sk_ptr)

      ! Fail-closed gate: halt if MMP violated (spectral instability)
      if (current_multiplicity > multiplicity_bound) then
        call sov_bifrost_sign_scalar("QMHES_MMP_VIOLATION", current_multiplicity, sk_ptr)
        out_rho = rho
        deallocate(U, evolved)
        return
      end if
    end block

    ! ═══════════════════════════════════════════════════════════════
    ! SNDL KEY FRESHNESS GATE: Prevent replay attacks (Store Now defense)
    ! Key bound to WORM chain β†’ harvested data useless without future WORM state
    ! Any interception alters [U,ρ*]=0 β†’ key corruption β†’ WORM mismatch
    ! ═══════════════════════════════════════════════════════════════
    block
      integer(i8), target :: freshness_hash(32), latest_worm_hash(32)
      logical :: is_fresh
      integer(c_int64_t) :: fh_idx

      interface
        subroutine sndl_freshness_hash(rho_ptr, n_dim, out_ptr) &
            bind(C, name="sndl_freshness_hash")
          import :: c_ptr, c_int64_t
          type(c_ptr), value :: rho_ptr
          integer(c_int64_t), value :: n_dim
          type(c_ptr), value :: out_ptr
        end subroutine
      end interface

      ! Generate key freshness hash from current density matrix (post-JST)
      call sndl_freshness_hash(c_loc(out_rho), n, c_loc(freshness_hash))

      ! Fetch latest SNDL key entry from WORM chain
      call worm_get_latest_hash("SNDL_KEY_FRESHNESS", latest_worm_hash)

      ! Check for replay: freshness hash must differ from last attested
      is_fresh = .false.
      do fh_idx = 1, 32
        if (freshness_hash(fh_idx) /= latest_worm_hash(fh_idx)) then
          is_fresh = .true.
          exit
        end if
      end do

      ! WORM-attest freshness check
      call sov_bifrost_sign_bytes("SNDL_KEY_FRESHNESS", freshness_hash, 32, sk_ptr)

      ! Fail-closed gate: halt if key is stale (replay attempt)
      if (.not. is_fresh) then
        call sov_bifrost_sign_bytes("SNDL_REPLAY_ATTACK", freshness_hash, 32, sk_ptr)
        out_rho = rho
        deallocate(U, evolved)
        return
      end if
    end block

    call sov_blake3_hash_matrix(out_rho, int(n), hash_ptr)
    call sov_bifrost_sign(hash_ptr, int(32, c_size_t), sk_ptr, sig_ptr)

    deallocate(U, evolved)
  end subroutine

  !═══════════════════════════════════════════════════════════════════
  ! jordan_fib β€” depth-N Fibonacci tower of Jordan blocks
  !
  ! {-@ jordan_fib :: {n:Int | n > 0}
  !                β†’ Vec n (Hermitian d Γ— Float)   -- (H_k, dt_k)
  !                β†’ Density d
  !                β†’ (Density d, Vec n Receipt)    @-}
  !
  ! APL:  ρ ← \ (jordan_step ⍒ H_k dt_k) over layers    β€” scan \
  !       Each layer contracts at rate φ⁻¹; tower at rate φ⁻ᴺ
  !═══════════════════════════════════════════════════════════════════
  subroutine jordan_fib(H_list_ptr, dt_list_ptr, n_layers, n, &
       rho_ptr, receipts_ptr, sk_ptr, pk_ptr, converged) &
       bind(C, name="jordan_fib")
    type(c_ptr),        intent(in),  value :: H_list_ptr, dt_list_ptr
    integer(c_int64_t), intent(in),  value :: n_layers, n
    type(c_ptr),        intent(in),  value :: rho_ptr, receipts_ptr
    type(c_ptr),        intent(in),  value :: sk_ptr, pk_ptr
    integer(c_int64_t), intent(out)        :: converged

    complex(dp), pointer :: H_list(:,:,:), rho(:,:)
    real(dp),    pointer :: dt_list(:)
    integer(i8), pointer :: receipts(:)
    complex(dp), allocatable, target :: rho_cur(:,:), rho_nxt(:,:)
    real(dp) :: fib_a, fib_b, fib_c, diff_norm
    integer(c_int64_t) :: k, i, j
    integer(c_int64_t), parameter :: RECEIPT_SZ = 96
    type(c_ptr) :: hash_ptr, sig_ptr  ! 32 hash + 64 sig

    call c_f_pointer(H_list_ptr,  H_list,   [n_layers, n, n])
    call c_f_pointer(dt_list_ptr, dt_list,  [n_layers])
    call c_f_pointer(rho_ptr,     rho,      [n, n])
    call c_f_pointer(receipts_ptr,receipts, [n_layers * RECEIPT_SZ])

    allocate(rho_cur(n,n), rho_nxt(n,n))
    rho_cur = rho

    ! Fibonacci convergence tracking: F_{k-1}, F_k, F_{k+1}
    fib_a = 1.0_dp; fib_b = 1.0_dp   ! F_0=1, F_1=1

    converged = 0

    ! APL: ρ ← \ jordan_step over H_list    β€” prefix scan across layers
    do k = 1, n_layers
      hash_ptr = c_loc(receipts((k-1)*RECEIPT_SZ + 1))
      sig_ptr  = c_loc(receipts((k-1)*RECEIPT_SZ + 33))

      call jordan_step(c_loc(H_list(k,:,:)), c_loc(rho_cur), n, &
           dt_list(k), sk_ptr, pk_ptr, &
           c_loc(rho_nxt), hash_ptr, sig_ptr)

      ! Track ‖ρ_{k+1} βˆ’ ρ_kβ€–_F  β€” Fibonacci decay check
      diff_norm = 0.0_dp
      do i = 1, n; do j = 1, n
        diff_norm = diff_norm + abs(rho_nxt(i,j) - rho_cur(i,j))**2
      end do; end do
      diff_norm = sqrt(diff_norm)

      ! Fibonacci recurrence on contraction bound
      fib_c = fib_a + fib_b; fib_a = fib_b; fib_b = fib_c
      ! Banach bound: diff_norm ≀ C Β· φ⁻ᡏ
      if (diff_norm < PHI_INV**k * 1.0e-6_dp) converged = k

      rho_cur = rho_nxt
    end do

    rho = rho_cur
    deallocate(rho_cur, rho_nxt)
  end subroutine

  !═══════════════════════════════════════════════════════════════════
  ! jordan_fixpoint β€” iterate until Banach convergence
  !
  ! {-@ jordan_fixpoint :: Hermitian d β†’ Float β†’ Density d
  !                     β†’ {ρ* : Density d | T ρ* = ρ*}          @-}
  !
  ! APL:  ρ* ← H ⍣≑ jordan_step    β€” APL power to fixpoint ⍣≑
  !       Guaranteed to converge by Banach: T is φ⁻¹-contraction
  !═══════════════════════════════════════════════════════════════════
  subroutine jordan_fixpoint(H_ptr, rho_ptr, n, dt, sk_ptr, pk_ptr, &
       max_iter, tol, iterations, hash_ptr, sig_ptr) &
       bind(C, name="jordan_fixpoint")
    type(c_ptr),        intent(in),  value :: H_ptr, rho_ptr
    integer(c_int64_t), intent(in),  value :: n, max_iter
    real(dp),           intent(in),  value :: dt, tol
    type(c_ptr),        intent(in),  value :: sk_ptr, pk_ptr
    integer(c_int64_t), intent(out)        :: iterations
    type(c_ptr),        intent(in),  value :: hash_ptr, sig_ptr

    complex(dp), pointer :: rho(:,:)
    complex(dp), allocatable, target :: rho_nxt(:,:)
    real(dp) :: diff_norm
    integer(c_int64_t) :: k, i, j

    call c_f_pointer(rho_ptr, rho, [n, n])
    allocate(rho_nxt(n,n))

    ! APL: ρ* ← H ⍣≑ T    β€” iterate T until fixed point
    iterations = 0
    do k = 1, max_iter
      call jordan_step(H_ptr, rho_ptr, n, dt, sk_ptr, pk_ptr, &
           c_loc(rho_nxt), hash_ptr, sig_ptr)

      diff_norm = 0.0_dp
      do i = 1, n; do j = 1, n
        diff_norm = diff_norm + abs(rho_nxt(i,j) - rho(i,j))**2
      end do; end do
      diff_norm = sqrt(diff_norm)

      rho = rho_nxt
      iterations = k

      ! Banach: convergence guaranteed, just check threshold
      if (diff_norm < tol) exit
    end do

    deallocate(rho_nxt)
  end subroutine

  !═══════════════════════════════════════════════════════════════════
  ! jordan_gradient β€” adjoint method: βˆ‚L/βˆ‚H via reverse evolution
  !
  ! {-@ jordan_gradient :: Density d β†’ Density d β†’ Hermitian d
  !                     β†’ {dH : Hermitian d | dH† = dH}          @-}
  !
  ! APL:  Ξ» ← ⌽ (backward jordan_step) over [ρ_T .. ρ_0]   β€” reverse ⌽
  !       βˆ‚L/βˆ‚H ← +/ (Ξ»_k βŠ— ρ_k)                           β€” outer ∘.Γ—
  !═══════════════════════════════════════════════════════════════════
  subroutine jordan_gradient(rho_fwd_ptr, lambda_ptr, n, dt, dH_ptr) &
       bind(C, name="jordan_gradient")
    type(c_ptr),        intent(in),  value :: rho_fwd_ptr, lambda_ptr, dH_ptr
    integer(c_int64_t), intent(in),  value :: n
    real(dp),           intent(in),  value :: dt

    complex(dp), pointer :: rho_fwd(:,:), lambda(:,:), dH(:,:)
    integer(c_int64_t) :: i, j, ii, k
    complex(dp) :: comm
    real(dp) :: eigval_approx, entropy_bound, delta_t
    logical :: anomaly_detected

    call c_f_pointer(rho_fwd_ptr, rho_fwd, [n, n])
    call c_f_pointer(lambda_ptr,  lambda,  [n, n])
    call c_f_pointer(dH_ptr,      dH,      [n, n])

    ! APL: dH ← -iΒ·dt Β· (Ξ» ∘.Γ— ρ βˆ’ ρ ∘.Γ— Ξ»)    β€” commutator outer product
    !      = -i·dt·[λ, ρ]   (Lie bracket / commutator)
    !$omp parallel do collapse(2) default(none) &
    !$omp shared(dH,lambda,rho_fwd,n,dt) private(i,j,k)
    do i = 1, n
      do j = 1, n
        comm = czero
        do k = 1, n
          comm = comm + lambda(i,k)*rho_fwd(k,j) - rho_fwd(i,k)*lambda(k,j)
        end do
        ! Gradient = -i·dt·[λ,ρ], projected to Hermitian (take real part of i·comm)
        dH(i,j) = (-ci) * dt * comm * PHI_INV  ! Fibonacci-weighted gradient
      end do
    end do
    !$omp end parallel do

    ! Project to Hermitian: dH ← Β½(dH + dH†)
    !$omp parallel do collapse(2) default(none) shared(dH,n) private(i,j)
    do i = 1, n
      do j = 1, n
        dH(i,j) = 0.5_dp * (dH(i,j) + conjg(dH(j,i)))
      end do
    end do
    !$omp end parallel do
  end subroutine

end module jordan_block