0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

付録I 周期 lift 構造有限検査証明書

0
Last updated at Posted at 2026-08-02

【論文編 - 付録I(日本語草稿版)】

 本稿は、「コラッツ予想の証明 - 未解決問題への挑戦」の付録I です。
直接には、論文の第3章から参照されます。

 必要に応じて、以下の本編を参照願います。

付録目次

付録I 周期 lift 構造有限検査証明書
 I.1 目的
 I.2 有限検査証明の概要
  I.2.1 本文との対応関係
  I.2.2 サポート範囲
  I.2.3 証明対象
  I.2.4 有限検査への帰着
  I.2.5 処理方式
 I.3 検査モード
  I.3.1 モード一覧
  I.3.2 正式採用モード
  I.3.3 補助確認モード
 I.4 有限検査証明
  I.4.1 有限還元
  I.4.2 正整数周期 lift の完全分類
  I.4.3 自明なループの確認
  I.4.4 構造値の導出と確定判定
  I.4.5 検証結果
 I.5 周期 lift 構造有限検査証明書
  I.5.1 2層 core certificate の構成
  I.5.2 正式採用モード
  I.5.3 証明書本体
  I.5.4 証明書項目の概要
  I.5.5 証明書の識別
  I.5.6 Layer 1 の証拠
  I.5.7 Layer 2 の証拠
  I.5.8 独立検証
  I.5.9 適用範囲
  I.5.10 証明書の同一性・完全性確認
 I.6 実行環境
  I.6.1 ソフトウェア要件
  I.6.2 対応環境
  I.6.3 実行リソース
  I.6.4 有用性と限界
 I.7 再現手順
  I.7.1 推奨コマンド
  I.7.2 周期 lift 構造有限検査証明書の生成
  I.7.3 独立検証の実行
  I.7.4 正常終了の判定
  I.7.5 成果物
  I.7.6 実行実績
 I.8 コマンド・リファレンス
  I.8.1 統一コマンド
  I.8.2 オプション一覧
  I.8.3 既定値と出力先
  I.8.4 heartbeat ログ形式
 I.9 検証プログラムの構成
  I.9.1 概要
  I.9.2 プログラム構造
  I.9.3 処理フロー
  I.9.4 証明書生成系
  I.9.5 独立検証系
 I.10 リソースと版情報
  I.10.1 実行パッケージ
  I.10.2 実行時必要ファイルと配布資料の区別
  I.10.3 実行時 source integrity と配布物の完全性確認
  I.10.4 版情報
 I.11 実行時必要ファイル一覧
 I.12 検証プログラムのソースコード
  I.12.1 ctv0100.py
  I.12.2 ctv_environment_snapshot.py
  I.12.3 ctv_internal_console_log.py
  I.12.4 LIC_appendix_i_core_certificate.py
  I.12.5 LIC_appendix_i_core_certificate_verifier.py
  I.12.6 LIC_certificate_logical_paths.py
  I.12.7 LIC_certificate_metadata.py
  I.12.8 LIC_complete_cycle_classification.py
  I.12.9 LIC_complete_cycle_classification_verifier.py
  I.12.10 LIC_constants.py
  I.12.11 LIC_core_manager.py
  I.12.12 LIC_cycle_minimum_audit.py
  I.12.13 LIC_cycle_minimum_audit_verifier.py
  I.12.14 LIC_cycle_minimum_bound.py
  I.12.15 LIC_finite_lp_cycle_bridge.py
  I.12.16 LIC_finite_lp_cycle_bridge_verifier.py
  I.12.17 LIC_phase_b_structure.py
  I.12.18 LIC_phase_b_structure_verifier.py
  I.12.19 LIC_r_logical_graph.py
  I.12.20 LIC_r_micrograph.py
  I.12.21 LIC_r_transition.py
  I.12.22 LIC_status.py
  I.12.23 LIC_structural_lambda_certificate.py
  I.12.24 LIC_structural_lambda_certificate_verifier.py
  I.12.25 LIC_version.py

付録I 周期 lift 構造有限検査証明書

I.1 目的

 本付録では、本文第 3 章の周期 lift 構造有限検査証明書の
証拠構造、独立検証方式および再現手順を示す。
 検証プログラムが出力した周期 lift 構造有限検査証明書を
証明書本体としてそのまま掲載し、その生成方式、2層証拠構造、
構造値の確定判定、独立検証、適用範囲、および再現方法を説明する。

I.2 有限検査証明の概要

 ここでは、周期 lift 構造有限検査証明書に関する概要を示す。
周期 lift 構造有限検査証明書は、検証プログラムが生成する。

I.2.1 本文との対応関係

 本文の第 3 章は、有限状態 LP、正整数周期 lift、周期最小値候補の
有限監査および有効 LP 可行解構造を数学的に定式化する。
 本付録は、その定式化に対応する有限検査を実行し、
証明書と独立検証結果を提示する。

 本付録では、周期 lift 構造有限検査証明書の本体、生成方式、証拠構造、
独立検証および再現方法を詳述する。

I.2.2 サポート範囲

 本付録に属する検証プログラムがサポートする法 $M$ は次である。

M = 1024, 2048, 4096, 8192, 16384, 32768, 65536

 いずれのサポート値についても、同一構造の
周期 lift 構造有限検査証明書、独立検証結果および関連証拠を生成する。
 成果物名には対象 $M$ を含める。現行論文では $M = 4096$ の証明書を
採用するが、将来、採用値を変更する場合もプログラム改修を必要とせず、
対象モードで生成された証明書を選択できる。

I.2.3 証明対象

 周期 lift 構造有限検査証明書が直接対象とするのは、指定したモードの
exact $R$-micrograph から構成される derived logical $R$-graph における
simple extreme-cycle 候補の正整数周期 lift 完全分類と、その分類結果から
得られる構造下界値 $\lambda_x^{\mathrm{str}} = 1$ である。

 検証プログラムは、各 $M$ に対して、周期 lift 構造有限検査証明書の
中核を構成する同一構造の2層 core certificate を生成する。
 $M = 4096$ は、コマンドの既定値および現行論文の採用値であるが、
証明書生成の特別条件ではない。

 具体的には、各モードについて次を確認する。

  • exact $R$-micrograph および derived logical $R$-graph が
    厳密に構成される。
  • finite circulation の extreme structure が simple directed cycle により
    表される。
  • 正整数周期 lift 候補の最小奇数値が有限上界以下に限定される。
  • 上界以下の全奇数最小値候補が漏れなく監査される。
  • 復帰候補が自明なループだけである。
  • 有効周期 lift 構造の構造値が厳密に $\lambda_x^{\mathrm{str}} = 1$ である。

I.2.4 有限検査への帰着

 法 $M$ に対する derived logical $R$-graph は有限状態グラフである。
simple directed cycle の長さは有限状態数以下に制限されるため、
正式採用モードでは最大長を、

N_M = \frac{M}{2}.

とする。

 各 cycle 長に対して周期最小値上界を計算し、それらの最大値を
$B_M^{\mathrm{global}}$ とする。正整数周期 lift が存在する場合、
その周期最小値はこの上界以下に限定される。
 したがって、上界以下の全正奇数を実際の $R()$ 遷移で監査する
ことにより、対象候補を有限個へ帰着できる。

I.2.5 処理方式

 検証プログラムは、概ね次の順序で処理する。

実行環境・source integrity 確認
  ↓
exact R-micrograph 構成
  ↓
derived logical R-graph 構成
  ↓
finite circulation bridge 確認
  ↓
cycle長ごとの周期最小値上界計算
  ↓
全奇数最小値候補監査
  ↓
Layer 1証明書生成・独立検証
  ↓
Layer 2証明書生成・独立検証
  ↓
2層core certificate生成・独立検証
  ↓
実行ログおよび成果物ZIP生成

I.3 検査モード

 本付録に属する検証プログラムがサポートするモードの詳細を示す。

I.3.1 モード一覧

 検証プログラムがサポートするモードの位置付けを以下とする。

$M$ $b$ 奇数有限状態数 $M/2$ 位置付け
1024 10 512 △
2048 11 1024 △
4096 12 2048 〇
8192 13 4096 △
16384 14 8192 △
32768 15 16384 △
65536 16 32768 △

(凡例)
  〇:公式の周期 lift 構造有限検査証明書として提示するモード。
  △:正式採用可能な補助確認モード。

I.3.2 正式採用モード

 現行論文の正式採用モードは、

b = 12, \qquad M = 2^{12} = 4096, \qquad N_M = 2048.

である。本モードで生成された2層 core certificate を、本文第 3 章および
本付録における周期 lift 構造有限検査証明書として採用する。
 なお、この採用は論文上の選択であり、検証プログラムは、
他のサポートモードについても同一形式の証明書を生成する。

I.3.3 補助確認モード

 補助確認モードは、正式採用モードと同じ数学的処理、証明書生成
および独立検証を、異なる有限状態規模で実行する。
 各モードは、それぞれ単独で完結した周期 lift 構造有限検査証明書の
2層 core certificate を生成する。

 現行論文では $M = 4096$ を採用するが、補助確認モードの証明書も、
実装の回帰確認、処理規模の確認、環境間再現性の確認、および
将来の採用モード変更の候補として保持できる。

I.4 有限検査証明

I.4.1 有限還元

 有限還元は、finite circulation の extreme structure を
simple directed cycle へ帰着し、cycle 長を $N_M$ 以下に制限した上で、
各 cycle 長の正整数周期 lift 候補を周期最小値上界以下の全奇数候補へ
還元する処理である。

 正式採用モードでは、最大 simple logical cycle 長は $2048$ であり、
全 cycle 長に対する global minimum-value bound は、

B_M^{\mathrm{global}} = 583287.

である。
 全長別上界の行数は $2048$ であり、この最大値は $L = 1636$ で
達成される。周期 lift 構造有限検査証明書には、行数、最大値、
最大達成長および、それらの独立検証状態が明示される。

I.4.2 正整数周期 lift の完全分類

 上界以下の正奇数候補数は、

\frac{583287 + 1}{2} = 291644.

である。
 検証プログラムは、この $291644$ 件を全て監査する。
周期 lift 構造有限検査証明書には、期待件数と実監査件数を
別項目として記録し、両者の一致、候補 block の完全一致および
監査全体の独立検証結果を明示する。

 監査結果は、次である。

RETURNED_TO_START            : 1
DESCENDED_BELOW_START        : 291643
NO_RETURN_WITHIN_MAX_LENGTH  : 0
nontrivial returned candidates: 0

 したがって、未判定候補は存在せず、非自明な復帰候補も存在しない。

I.4.3 自明なループの確認

 唯一の復帰候補は、

1 -> 1, T = (2)

である。これは本文で定義する自明なループに対応する。

I.4.4 構造値の導出と確定判定

 Layer 1 の独立検証により、有効な正整数周期 lift extreme structure は
自明なループだけである。
 自明なループでは、一回の奇数遷移における総除算回数が $2$であり、
追加除算回数は $1$である。

 したがって、有効周期 lift 構造の正規化凸結合における構造値は、

\lambda_x^{\mathrm{str}} = 1.

となる。この値は Layer 2 により独立に再構成される。

 本文§3.5.2では、第3章の論理から期待される構造値を、

\lambda_{x,\mathrm{expected}}^{\mathrm{str}} = 1.

と定める。ただし、この期待値は、探索条件、候補除外条件または
構造値の計算条件には使用しない。
 検証プログラムは、期待値とは独立に正整数周期 lift 候補を完全分類し、
その結果から有効な全extreme structureの構造値集合を再構成する。

 Layer 1 の完全分類、全候補監査、未判定候補ゼロおよびLayer 2 の
独立再構成が成立し、再構成された構造値集合が厳密に、

\left\{\lambda_x^{\mathrm{str}}\right\}=\left\{1\right\}.

となり、期待値と一致した場合、構造値は $\lambda_x^{\mathrm{str}}=1$ に
確定したものとする。この総合判定を Fixed と呼ぶ。
 前提となる証拠および独立検証が全て成立したものの、再構成された
構造値集合が期待される単集合 ${1}$ ではない場合、または再構成結果が
期待値 $1$ と一致しない場合は、確定判定を NOT_FIXED とする。
 前提証拠または独立検証が成立していない場合は、構造値が $1$ でないと
判定するのではなく、確定判定自体を UNVERIFIED とする。

I.4.5 検証結果

 正式採用モードでは、Layer 1、Layer 2 および2層 core certificate の
全てが独立検証に合格した。2層 core certificate の最終状態は、

PASS

である。
 また、構造値の実測値、期待値、再構成値集合および確定判定は、

structural value lambda_x^str                      : 1
expected structural value lambda_x^str             : 1
structural value lambda_x^str set                  : {1}
structural value lambda_x^str fixed judgment       : Fixed
structural value fixed judgment independent verify : PASS

である。

I.5 周期 lift 構造有限検査証明書

 周期 lift 構造有限検査証明書に関する詳細を以下に示す。

I.5.1 2層 core certificate の構成

 本文第3章で定義する周期 lift 構造有限検査証明書は、
前節までに示した数学的な有限還元と、有限個に限定された全候補の
完全監査および独立検証を組み合わせて成立する。
 本節でいう2層 core certificate は、その有限検査結果を役割の異なる
次の2つの証拠層に分けて束縛した証明書本体である。

Layer 1 : 正整数周期 lift の完全分類
Layer 2 : Layer 1 の分類結果から構造値 lambda_x^str = 1 を独立再構成

 Layer 1 は正整数周期 lift 候補の完全分類とその独立検証結果を記録する。
Layer 2 は、Layer 1 で確認された有効extreme structure 集合から構造値を
独立に再構成する。Layer 2 はLayer 1 の完全分類を置き換えるものでは
なく、Layer 1 から得られる構造値の独立再計算層である。

 2層 core certificate は、数学的な有限還元を代替するものではない。
数学的な有限還元により限定された全対象が漏れなく監査され、
その分類結果、構造値、構造値の確定判定および各独立検証が
成立したことを示す中核証拠である。

 証明書の schema、項目順序および検証方式は全サポート $M$ で
共通であり、状態数、上界、監査件数、hash、日時等の値が
対象モードに応じて変化する。

I.5.2 正式採用モード

 本節掲載の証明書本体は、現行の正式採用モード $M = 4096$ に対して、
著者のローカル環境で現行プログラム正本を実行して生成したものである。
本文第 3 章§3.5.2 に掲載された周期 lift 構造有限検査証明書と、
本節に掲載する証明書は、同一の生成結果である。

 実行時には $M = 4096$ を明示指定し、
--author-idおよび--operator-idの双方に著者固有 UUID を指定した。
生成された周期 lift 構造有限検査証明書では、著者 ID、生成作業者 ID
および検証作業者 ID が同一の著者固有 UUID として記録されている。
 本証明書は、schema v7 により、Layer 1、Layer 2、実測構造値、
期待構造値、再構成構造値集合、構造値の確定判定 Fixed および
その独立検証を記録する。

 正式証明書の実行コマンドは次である。

python -u ctv0100.py --M 4096 --author-id "cc28ae4b-b063-45af-ac0d-0ef67e0325e6" --operator-id "cc28ae4b-b063-45af-ac0d-0ef67e0325e6"

I.5.3 証明書本体

 以下は、検証プログラムが生成した周期 lift 構造有限検査証明書の
全文である。この内容は本文第3章へそのまま反映される。

finite-check certificate id                        : LIC-APPENDIX-I-CORE-CERTIFICATE-v7
package label                                      : X04a-D01
b                                                  : 12
M                                                  : 4096
N_M                                                : 2048
certificate author id                              : cc28ae4b-b063-45af-ac0d-0ef67e0325e6
certificate generation operator id                 : cc28ae4b-b063-45af-ac0d-0ef67e0325e6
certificate verification operator id               : cc28ae4b-b063-45af-ac0d-0ef67e0325e6
certificate generator program id                   : LIC_appendix_i_core_certificate
certificate verifier program id                    : LIC_appendix_i_core_certificate_verifier
finite-check certificate created at                : 2026-08-02 18:01:15 JST
finite-check certificate verified at               : 2026-08-02 18:01:19 JST
finite-check certificate verification status       : PASS
exact R-micrograph state count                     : 6144
exact R-micrograph microedge count                 : 10240
exact R-micrograph hash payload fields             : M, states, edges
exact R-micrograph SHA-256                         : 51383ba07bc502baafdc12f659bc6cb6a8e8c10e0d612501d43494c598150cbb
exact R-micrograph state-set verify                : PASS
exact R-micrograph microedge-set verify            : PASS
exact R-micrograph transition verify               : PASS
exact R-micrograph independent verify              : PASS
derived logical R-graph odd state count            : 2048
derived logical R-graph logical edge count         : 26624
derived logical R-graph hash payload fields        : edge_id, src, dst, t, additional_division_cost, transformed_weight, micro_edge_ids
derived logical R-graph SHA-256                    : 2e31bc56f384b844439158e1bf70c543d980bce48065fb5029e58ccc46d0f690
derived logical R-graph odd-state-set verify       : PASS
derived logical R-graph edge-set verify            : PASS
logical-edge microedge-sequence verify             : PASS
logical-edge division-label verify                 : PASS
derived logical R-graph hash-binding verify        : PASS
derived logical R-graph independent verify         : PASS
finite circulation bridge graph binding verify     : PASS
finite circulation bridge length verify            : PASS
finite circulation bridge independent verify       : PASS
minimum-bound length rows                          : 2048
global minimum-value bound B_M^global              : 583287
global bound attained at L                         : 1636
minimum-bound lengths SHA-256                      : dc42e09ef7af729a143ba5ba537e7b7e7b686501e242d8278b2bec24f645bb9f
all-length bounds exact/maximal verify             : PASS
global minimum-value bound verify                  : PASS
global-bound argmax verify                         : PASS
minimum-bound independent verify                   : PASS
odd minimum candidates expected                    : 291644
odd minimum candidates audited                     : 291644
odd minimum candidate coverage complete            : PASS
candidate-count independent verify                 : PASS
candidate-blocks independent verify                : PASS
minimum-candidate audit independent verify         : PASS
RETURNED_TO_START                                  : 1
nontrivial returned candidates                     : 0
DESCENDED_BELOW_START                              : 291643
NO_RETURN_WITHIN_MAX_LENGTH                        : 0
trivial loop                                       : 1 -> 1, T = (2)
terminal-counts independent verify                 : PASS
returned-cycle details independent verify          : PASS
nontrivial-return-zero independent verify          : PASS
trivial-loop-only independent verify               : PASS
Layer 1 independent verify                         : PASS
Layer 2 independent verify                         : PASS
structural value lambda_x^str                      : 1
expected structural value lambda_x^str             : 1
structural value lambda_x^str set                  : {1}
structural value lambda_x^str fixed judgment       : Fixed
structural value fixed judgment independent verify : PASS
core certificate independent verify                : PASS
core certificate verified at                       : 2026-08-02 18:01:19 JST

I.5.4 証明書項目の概要

 下表は、証明書本体に出現する全項目を、出力順に説明したものである。
表中の「値の説明」は、各項目に記録された値が何を表すかを示す。
 「PASS 判定の意味」は、状態フラグが PASS の場合に成立する
確認内容を示す。
 数値、ID、日時、SHA-256 等の判定項目でないものは該当なしであり、
以下では「—」と表記する。

証明書項目 概要 値の説明 PASS判定の意味
finite-check certificate id 証明書識別 周期 lift 構造有限検査証明書の種別と schema 版を識別する固定 ID である。v7 は、通常状態値の正規化に加えて、期待構造値、再構成値集合、構造値の確定判定およびその独立検証を含む schema 版を示す。 —
package label 版識別 この証明書を生成した Core Program 版を示す。この値により、証明書と実装版を対応付ける。 —
b 検査条件 法を M = 2^b と表したときの指数である。掲載証明書では値 12 であり、$M=4096$ に対応する。 —
M 検査条件 有限状態分類に用いる法である。掲載証明書の値 4096 は、現行論文で採用する検査値である。 —
N_M 検査条件 derived logical R-graphで監査する simple logical cycle の最大長である。値 2048 = M/2 を示す。 —
certificate author id 主体識別 論文および証明体系の著者を識別する固定 UUID である。 —
certificate generation operator id 作業識別 証明書生成処理を実行した作業者 UUID である。 —
certificate verification operator id 作業識別 独立検証処理を実行した作業者 UUID である。 —
certificate generator program id Program識別 周期 lift 構造有限検査証明書を生成したプログラムの固定 ID である。 —
certificate verifier program id Program識別 周期 lift 構造有限検査証明書を独立検証したプログラムの固定 ID である。 —
finite-check certificate created at 日時 周期 lift 構造有限検査証明書本体が生成された日時を JST で示す。 —
finite-check certificate verified at 日時 周期 lift 構造有限検査証明書の独立検証が完了した日時を JST で示す。 —
finite-check certificate verification status 総合判定 周期 lift 構造有限検査証明書全体に対する独立検証の最終状態である。 PASS は、証明書 schema、識別情報、子証拠、事実値、状態フラグおよび最終状態の全検査に合格したことを示す。
exact R-micrograph state count exact R-micrograph exact R-micrograph に含まれる全state数である。値 6144 は正式採用モードで構成された state 総数を示す。 —
exact R-micrograph microedge count exact R-micrograph exact R-micrograph に含まれる全 microedge 数である。値 10240 は構成された microedge 総数を示す。 —
exact R-micrograph hash payload fields exact R-micrograph graph identity 用 SHA-256 を計算する際に正規化 payload へ含める field 群を示す。 —
exact R-micrograph SHA-256 exact R-micrograph 指定payload から計算した exact R-micrograph の同一性確認値である。 —(hash 値であり、判定は対応する検証項目で示す)
exact R-micrograph state-set verify exact R-micrograph state集合が独立再構成結果と完全一致するかを示す。 PASS は、state の欠落、余分な state または値の不一致がないことを示す。
exact R-micrograph microedge-set verify exact R-micrograph microedge 集合が独立再構成結果と完全一致するかを示す。 PASSは、microedgeの欠落、重複、余分な edge または属性不一致がないことを示す。
exact R-micrograph transition verify exact R-micrograph 各 microedge の遷移関係がR遷移定義と一致するかを示す。 PASS は、全 microedgeの始点・終点・遷移内容が独立計算と一致することを示す。
exact R-micrograph independent verify exact R-micrograph exact R-micrograph に対する独立検証全体の集約状態である。 PASS は、state集合、microedge 集合、遷移構造およびgraph identity の全検査に合格したことを示す。
derived logical R-graph odd state count derived logical R-graph derived logical R-graph に含まれる奇数 state 数である。値 2048 = M/2 を示す。 —
derived logical R-graph logical edge count derived logical R-graph derived logical R-graphに含まれる logical edge 総数である。値 26624 を示す。 —
derived logical R-graph hash payload fields derived logical R-graph logical graph identity 用 SHA-256 に束縛する各 edge の field 群を示す。 —
derived logical R-graph SHA-256 derived logical R-graph 指定 payload から計算した derived logical R-graph の同一性確認値である。 —(hash 値であり、判定は対応する検証項目で示す)
derived logical R-graph odd-state-set verify derived logical R-graph 奇数 state 集合が独立再構成結果と一致するかを示す。 PASS は、奇数 state 集合の欠落、重複または余分な state がないことを示す。
derived logical R-graph edge-set verify derived logical R-graph logical edge 集合が独立再構成結果と一致するかを示す。 PASS は、logical edge の欠落、重複、余分な edge または属性不一致がないことを示す。
logical-edge microedge-sequence verify derived logical R-graph 各logical edge が保持する ordered microedge 列を独立に照合した状態である。 PASS は、全 logical edge の microedge 列が exact R-micrograph 上の対応パスと一致することを示す。
logical-edge division-label verify derived logical R-graph 各logical edge の除算回数 label 等を独立計算と照合した状態である。 PASS は、除算回数および追加除算寄与を含む label が全 edge で一致することを示す。
derived logical R-graph hash-binding verify derived logical R-graph logical graph の SHA-256 が指定 payload 全体を正しく束縛しているかを示す。 PASS は、証明書内の graph hash と独立再計算 hash が一致することを示す。
derived logical R-graph independent verify derived logical R-graph derived logical R-graph に対する独立検証全体の集約状態である。 PASS は、state 集合、edge 集合、microedge 列、label および hash binding の全検査に合格したことを示す。
finite circulation bridge graph binding verify finite circulation bridge bridge 証拠が対象 derived logical R-graph を正しい identity で参照しているかを示す。 PASS は、bridge 証拠が検証対象 graph へ SHA-256 等で正しく束縛されていることを示す。
finite circulation bridge length verify finite circulation bridge simple extreme-cycle の長さ上限が有限奇数 state 数 N_M と一致するかを示す。 PASS は、最大長が N_M = 2048 として正しく確認されたことを示す。
finite circulation bridge independent verify finite circulation bridge finite circulation と simple directed cycle の bridge 全体に対する独立検証状態である。 PASS は、graph binding および長さ上限を含む bridge 証拠の全検査に合格したことを示す。
minimum-bound length rows 周期最小値上界 cycle長 L = 1, ..., N_M 毎の上界行数である。値 2048 は全長が欠落なく収録されたことを示す事実値である。 —
global minimum-value bound B_M^global 周期最小値上界 全 cycle 長別上界 B_L の最大値である。値 583287 が全奇数最小値候補監査の上限となる。 —
global bound attained at L 周期最小値上界 global bound を達成する cycle長 である。値 1636 で最大値 583287 が達成されたことを示す。 —
minimum-bound lengths SHA-256 周期最小値上界 全長別上界表の同一性・完全性を確認する SHA-256 である。 —(hash 値であり、判定は対応する検証項目で示す)
all-length bounds exact/maximal verify 周期最小値上界 全 1 <= L <= N_M の B_L が正確であり、各長で最大性を満たすかを示す。 PASS は、2048 行すべてが独立再計算と一致し、各B_Lが所定の最大値であることを示す。
global minimum-value bound verify 周期最小値上界 B_M^global が全 B_L の最大値と一致するかを示す。 PASS は、記録値 583287 が全長別上界の最大値であることを示す。
global-bound argmax verify 周期最小値上界 global bound の最大達成長が正しいかを示す。 PASS は、記録された L = 1636 が最大値を達成する長として独立確認されたことを示す。
minimum-bound independent verify 周期最小値上界 周期最小値上界証拠全体に対する独立検証の集約状態である。 PASSは、全長行、各上界、global bound、argmax および表 hash の全検査に合格したことを示す。
odd minimum candidates expected 最小値候補監査 1 から B_M^global までの全正奇数の理論上の総数である。値 291644 を示す。 —
odd minimum candidates audited 最小値候補監査 実際に監査した正奇数最小値候補の総数である。値 291644 を示す。 —
odd minimum candidate coverage complete 最小値候補監査 期待候補集合と実監査候補集合が完全一致するかを示す。 PASS は、上界以下の全正奇数が一件の欠落・重複もなく監査されたことを示す。
candidate-count independent verify 最小値候補監査 期待件数と実監査件数を独立に照合した状態である。 PASS は、期待件数 291644 と実監査件数 291644 が一致することを示す。
candidate-blocks independent verify 最小値候補監査 分割保存された候補 block の範囲、連続性、重複および集約内容を検証した状態である。 PASS は、全 block が候補集合を欠落・重複なく構成することを示す。
minimum-candidate audit independent verify 最小値候補監査 最小値候補監査全体に対する独立検証の集約状態である。 PASS は、候補網羅性、件数、block 構成、遷移分類および集計結果の全検査に合格したことを示す。
RETURNED_TO_START 監査分類結果 最大長以内に出発値へ復帰した候補数である。値 1 を示す。 —
nontrivial returned candidates 監査分類結果 復帰候補のうち自明なループ以外の候補数である。値 0 を示す。 —
DESCENDED_BELOW_START 監査分類結果 最大長以内に開始値未満へ下降した候補数である。値 291643 を示す。 —
NO_RETURN_WITHIN_MAX_LENGTH 監査分類結果 最大長以内に復帰も開始値未満への下降も確認されなかった候補数である。値 0 を示す。 —
trivial loop 監査分類結果 唯一の復帰候補の遷移内容である。1 -> 1, T = (2) を示す。 —
terminal-counts independent verify 監査分類検証 三分類の件数合計と監査総数、および各分類件数を独立に照合した状態である。 PASS は、復帰・下降・未判定の件数が相互に整合し、総監査件数と一致することを示す。
returned-cycle details independent verify 監査分類検証 復帰候補の開始値、長さ、ordered T-pattern および復帰先を独立に照合した状態である。 PASS は、唯一の復帰候補の詳細が 1 -> 1, T = (2) と一致することを示す。
nontrivial-return-zero independent verify 監査分類検証 非自明な復帰候補が存在しないことを独立に確認した状態である。 PASSは、非自明復帰候補数が厳密に 0 であることを示す。
trivial-loop-only independent verify 監査分類検証 正整数周期lift可能な復帰構造が自明なループだけであることの集約検証状態である。 PASS は、復帰候補が一件だけで、その一件が自明なループであり、非自明候補も未判定候補もないことを示す。
Layer 1 independent verify 2層証明書 正整数周期 lift 完全分類を担う Layer 1 全体の独立検証状態である。 PASS は、graph、bridge、全長別上界、全候補監査および完全分類証拠の全検査に合格したことを示す。
Layer 2 independent verify 2層証明書 Layer 1 の分類結果から構造値を再構成する Layer 2 全体の独立検証状態である。 PASS は、自明なループから構造値 lambda_x^str = 1 が独立に正確再構成されたことを示す。
structural value lambda_x^str 構造値 有効な正整数周期 lift 構造から独立再構成された実測構造値である。値 1 を示す。 —
expected structural value lambda_x^str 期待構造値 本文§3.5.2 で規定された期待構造値である。値 1 を示す。この値は探索、候補除外または構造値計算には使用せず、再構成結果との照合にのみ用いる。 —
structural value lambda_x^str set 再構成値集合 Layer 2 が有効な全 extreme structure から再構成した構造値集合である。値 {1} は、再構成値が厳密に単集合であることを示す。 —
structural value lambda_x^str fixed judgment 構造値確定判定 本文§3.5.2 の条件に基づく構造値固有の総合判定である。 Fixed は、完全分類、全候補判定、Layer 1・Layer 2 の独立検証、再構成値集合 {1} および期待値との一致がすべて成立したことを示す。NOT_FIXED は前提証拠成立後の不一致、UNVERIFIEDは前提証拠または独立検証の未成立を示す。
structural value fixed judgment independent verify 確定判定検証 下位証拠から構造値確定判定を独立に再計算し、証明書記録値と照合した状態である。 PASS は、独立再計算した判定がFixedであり、証明書記録値と一致することを示す。
core certificate independent verify core certificate Layer 1・Layer 2 と全子証拠を束縛する core certificate 全体の独立検証状態である。 PASS は、証明書 schema、全子証拠 hash、全事実値、全状態フラグ、Layer 1・Layer 2 および最終状態が整合したことを示す。
core certificate verified at 日時 core certificate 全体の独立検証完了日時を JST で示す。 —

I.5.5 証明書の識別

 証明書の識別情報は、次の役割を持つ。

項目 役割
finite-check certificate id 証明書 schema および証明書種別を識別する。
package label 証明書を生成した Core Program 版を識別する。
certificate author id 論文および証明体系の著者固有 UUID を示す。
certificate generation operator id 証明書生成を実行した作業者 UUID を示す。
certificate verification operator id 独立検証を実行した作業者 UUID を示す。
certificate generator program id 証明書生成プログラムを識別する。
certificate verifier program id 独立検証プログラムを識別する。
created at / verified at 作成日時および検証日時を示す。
verification status 独立検証の最終判定を示す。

 証明書著者 UUID は --author-id、証明書生成・独立検証処理の
作業者 UUID は --operator-idで指定する。通常の試験で
両オプションを省略した場合、統一コマンドは一回の実行につき
UUID v4 を一つ自動生成し、著者 ID、生成作業者 ID および
検証作業者 ID に共通して用いる。
 論文掲載用の正式な周期 lift 構造有限検査証明書を著者本人が生成し、
同一著者が独立検証処理の作業者となる形で作成する場合は、
著者固有 UUID を --author-id および --operator-idの双方に
明示指定する。
 なお、UUID の記録は作業識別のためのものであり、
公開鍵署名による本人性証明ではない。

I.5.6 Layer 1 の証拠

 Layer 1 は、次の証拠を束縛する。

証拠 内容
exact $R$-micrograph 状態数、microedge 数、遷移構造および graph identity を保持する。
derived logical $R$-graph 奇数状態、logical edge、各 edge の microedge 列、除算回数 label および graph identity を保持する。
finite circulation bridge finite circulation の extreme structure と simple directed cycle の対応を確認する。
全 cycle 長の上界証拠 $1 \le L \le N_M$ に対する周期最小値上界を確認する。
最小値候補監査 $B_M^{\mathrm{global}}$ 以下の全正奇数候補を直接監査する。
完全分類証明書 正整数周期 lift が自明なループだけであることを記録する。

 正式採用モードにおける Layer 1 の主要値は、次である。

maximum simple logical cycle length         : 2048
minimum-bound length rows                    : 2048
global minimum-value bound B_M^global        : 583287
global bound attained at L                   : 1636
all-length bounds exact/maximal verify       : PASS
odd minimum candidates expected              : 291644
odd minimum candidates audited               : 291644
odd minimum candidate coverage complete      : PASS
minimum-candidate audit independent verify   : PASS
positive-integer periodic lifts found        : 1
nontrivial positive-integer periodic lifts   : 0
trivial-loop-only independent verify         : PASS
status                                       : PASS

I.5.7 Layer 2 の証拠

 Layer 2 は、独立検証済みの Layer 1 証明書を入力とし、
有効な正整数周期 lift extreme structure が一つだけであることを
再確認する。
 その唯一の構造は、最小値 $1$、長さ $1$、ordered $T$-pattern $(2)$ の
自明なループである。

 この構造に対し、

sum_T                        : 2
sum_additional_divisions     : 1
structural lambda numerator  : 1
structural lambda denominator: 1
structural lambda exact      : 1

が成立する。Layer 2 の最終状態は、

PASS

である。

I.5.8 独立検証

 各証明書には、生成プログラムとは別の独立検証プログラムを用いる。

証明書 生成プログラム 独立検証プログラム
Layer 1 LIC_complete_cycle_classification LIC_complete_cycle_classification_verifier
Layer 2 LIC_structural_lambda_certificate LIC_structural_lambda_certificate_verifier
2層 core certificate LIC_appendix_i_core_certificate LIC_appendix_i_core_certificate_verifier

 検証プログラムでは、独立検証系の数学的再計算を
LIC_independent_ch3_math.pyへ分離した。
 同モジュールは Python 標準ライブラリだけを使用し、
証明書生成系の exact $R$-micrograph、derived logical $R$-graph、
周期最小値上界、候補監査および Phase-B 構造の実装を import しない。
 exact $R$-micrograph を明示的に再構築し、derived logical $R$-graph の
logical edge を経路毎の訪問済み内部状態集合を用いた独立探索で
列挙する。
 さらに、全長別上界を完全整数演算で再計算し、全奇数最小値候補を
独立に監査した上で、Layer 2 の構造値を再構成する。

 2層 core certificate の独立検証では、証明書 schema、著者 ID、
作業者 ID、日時、Program ID、証明範囲、2層構造、
子証拠の論理相対パス、ファイルサイズ、SHA-256、
Layer 1・Layer 2 の検証結果および最終状態を確認する。
 加えて、独立数学再構成層が有限グラフ、logical edge、全長別上界、
候補監査件数、監査網羅性、復帰候補分類および構造値を本文の定義から
再計算し、core certificate に記録された実際値と状態フラグを照合する。

I.5.9 適用範囲

 各モードの証明書が直接確立する対象は、次である。

M = <selected M> derived logical R-graph simple extreme-cycle
positive-integer periodic-lift complete classification
and the resulting structural value lambda_x^str = 1

 本節に掲載する証明書では、<selected M> は 4096 である。

 各証明書は、無制限の非周期無限経験フローに対する
平均追加除算回数の下界を証明書単独で直接主張しない。
 証明書の適用範囲を超える対象へ結論を拡張する場合は、
本文側で別途の数学的接続を示す必要がある。

I.5.10 証明書の同一性・完全性確認

 機械可読証明書、人間可読証明書および独立検証結果は、
対象 $M$ を識別可能な成果物名で同時に保存する。

成果物 役割
appendix_i_core_certificate_M<M>.json 対象 $M$ の機械可読正本証明書。
appendix_i_core_certificate_M<M>.txt 対象 $M$ の人間可読証明書表示。
appendix_i_core_certificate_M<M>_report.md 対象 $M$ の証明書概要報告。
appendix_i_core_certificate_M<M>_verify_summary.json 対象 $M$ の独立検証項目と結果。
appendix_i_core_certificate_M<M>.sha256 上記証明書成果物の同一性・完全性確認情報。

 証明書は、子証拠を論理相対パス、ファイルサイズおよび SHA-256 で
束縛する。
 絶対パス、親ディレクトリ参照および symlink artifact は許可しない。

I.6 実行環境

 ここでは、検証プログラムを実行する場合における要件と
動作環境等の概要を示す。

I.6.1 ソフトウェア要件

 検証プログラムの実行に必要なソフトウェアは次である。
記載している版数は、実行確認を行った最小バージョンを示す。

  • Python (3.12.13)
  • NumPy (2.0.2)
  • SciPy (1.16.3)

 なお、上記の内容は、利用時の参考情報である。

I.6.2 対応環境

 Core Program は、Python と必須ライブラリを利用できる
一般的な 64bit 環境を対象とする。動作実績のある環境は以下である。

  • MSYS2 in MS Windows
  • Google Colab
  • ChatGPT 内部環境

I.6.3 実行リソース

 必要時間およびメモリ使用量は、指定するモード $M$、CPU 性能、
Python・NumPy・SciPy 版および実行環境によって変化する。
 高位の $M$ では高負荷の長時間処理となる可能性があるため、
永続的な出力先、十分な空き容量および安定した実行環境を
使用することが望ましい。

I.6.4 有用性と限界

 検証プログラムにより、次が可能である。

  • サポートモードに対する周期 lift 構造有限検査証明書の生成
  • 本体数学実装に依存しない再構成を含む、Layer 1、Layer 2 および
    2層 core certificate の独立検証
  • 証明書、内部証拠、実行ログおよび結果 ZIP ファイルの保存
  • 著者 UUIDまたは作業者 UUID を記録した周期 lift 構造有限検査証明書の生成

 一方、次は直接の目的または保証対象ではない。

  • 任意の初期値に対する一般的なコラッツ状態探索
  • 論文本文の節、定理への適用説明または結論の自動生成
  • 無制限の非周期無限経験フローの直接分類
  • サポート外の $M$ に対する正常動作保証
  • UUID の記録だけによる作業者本人性の暗号学的証明
  • 実行環境の切断、記憶容量不足またはハードウェア障害の完全な防止

I.7 再現手順

 提供された検証プログラムにより、著者と同様の成果が得られる。
この作業のための再現手順の概要を以下に示す。

I.7.1 推奨コマンド

 通常実行の推奨コマンドは、次である。

python -u ctv0100.py --M 4096

 論文掲載用の正式な周期 lift 構造有限検査証明書を、著者本人が生成し、
同一著者が独立検証処理の作業者となる形で作成する場合は、
著者固有 UUID を --author-id と --operator-idの双方に指定する。
 掲載証明書では、論文著者の固有 UUID として
cc28ae4b-b063-45af-ac0d-0ef67e0325e6を用いている。

python -u ctv0100.py --M 4096 --author-id "cc28ae4b-b063-45af-ac0d-0ef67e0325e6" --operator-id "cc28ae4b-b063-45af-ac0d-0ef67e0325e6"

 --author-idは証明書の著者 UUID、
--operator-id は生成・独立検証処理を実行する作業者 UUID を指定する。
代理実行では両者を異なる値として指定可能である。
 通常の試験では両オプションを省略できる。省略した場合、
その実行過程専用の UUID v4 が自動生成され、その値が
著者 ID、生成作業者 ID および検証作業者 ID に共通して用いられる。

 推奨コマンド例は、実行目的を明確にするため、
必要最小限のオプションだけを示す。
出力先、run ID および heartbeat 間隔等は、必要な場合に個別に指定する。

I.7.2 周期 lift 構造有限検査証明書の生成

 検証プログラムは、環境確認、source integrity 確認、対象モードの
周期 lift 構造有限検査証明書を構成する2層 core certificate の生成、
外部独立検証および成果物パッケージングを順に実行する。
 例えば、--M 1024 を指定した場合は、次を生成する。

appendix_i_core_certificate_M1024.json
appendix_i_core_certificate_M1024.txt
appendix_i_core_certificate_M1024_report.md
appendix_i_core_certificate_M1024_verify_summary.json
appendix_i_core_certificate_M1024.sha256

 他のサポート $M$ についても、同じ命名規則で対象 $M$ に対応する
周期 lift 構造有限検査証明書を生成する。

I.7.3 独立検証の実行

 統一コマンドは、生成した対象 $M$ の証明書に対する独立検証まで
自動的に実行する。
 Core manager command を個別に使用する場合は、生成 run directory と
対象 $M$ を指定して、

python -u LIC_core_manager.py \
  verify-appendix-i-core-certificate \
  --run-dir <core-certificate-run-directory> \
  --M <M> \
  --operator-id <作業者自身のUUID>

を実行する。run directory に一つの対象 $M$ 証明書だけが存在する場合、
verifier は $M$ を自動判定できるが、再現手順では対象を明確にするため
--M の明示を推奨する。
 通常の再現試験で自動生成 UUID を用いる場合、--operator-id を
省略できる。
 正式な周期 lift 構造有限検査証明書を個別検証する場合は、
生成時と同じ著者固有 ID を指定する。

I.7.4 正常終了の判定

 コマンド実行が正常終了した場合、コンソールに次が表示される。

PASS: all four stages completed

 また、結果 ZIP ファイル名には _PASS.zip が付与され、
内部コンソールログ、結果 ZIP ファイルの SHA-256 および各証明書の
独立検証結果が生成される。

I.7.5 成果物

 主要成果物は、次である。

  • 対象 $M$ を名称に含む2層 core certificate 一式
  • Layer 1 証明書一式
  • Layer 2 証明書一式
  • 実行環境 snapshot
  • コマンド全体の内部コンソールログ
  • 実行サマリー
  • 成果物 ZIP ファイル
  • ZIP ファイルおよび主要証拠の SHA-256

I.7.6 実行実績

 検証プログラムの実行結果を次に示す。

 著者の MS Windows + MSYS2 環境では、$M=4096$ の正式証明書を、
著者固有 ID を --author-id および --operator-idに指定して生成した。
 証明書に記録された著者 ID、生成作業者 ID および検証作業者 ID は
全て cc28ae4b-b063-45af-ac0d-0ef67e0325e6 で一致する。
 証明書生成・独立検証、Layer 1、Layer 2、構造値の確定判定および
core certificate は全て PASS である。

$M$ 区分 実行環境 証明書生成 独立検証 検証項目 $\lambda_x^{\mathrm{str}}$ 状態
4096 正式証明書 MS Windows + MSYS2 PASS PASS 36/36 1 正式採用

 補助的な環境確認として、ChatGPT 内部環境では、通常実行の
$M = 1024,\ 2048,\ 4096,\ 8192,\ 16384$ を各々独立して実行した。

$M$ 区分 証明書生成 独立検証 packaging 検証項目 $\lambda_x^{\mathrm{str}}$ 状態
1024 通常単体 PASS PASS PASS 36/36 1 完了
2048 通常単体 PASS PASS PASS 36/36 1 完了
4096 通常単体 PASS PASS PASS 36/36 1 完了
8192 通常単体 PASS PASS PASS 36/36 1 完了
16384 通常単体 PASS PASS PASS 36/36 1 完了
32768 通常単体 — — — — — 未実施
65536 通常単体 — — — — — 未実施

 完了した全試験では、source integrity、Layer 1、Layer 2、
2層 core certificate、独立数学再構成および最終判定が全て PASS である。
非自明な正整数周期 liftは 0件、自明なループは1件、構造値は厳密に
$\lambda_x^{\mathrm{str}} = 1$ である。

 正式採用証明書の主要値は、$B_M^{\mathrm{global}}=583287$、
上界達成長 $L = 1636$、監査候補数 $291644$、RETURNED_TO_START = 1、
nontrivial returned candidates = 0、$\lambda_x^{\mathrm{str}} = 1$である。

I.8 コマンド・リファレンス

 検証プログラムを利用するためのコマンド仕様を以下に示す。

I.8.1 統一コマンド

ctv0100.py

は、周期 lift 構造有限検査証明書の生成と独立検証を
一つの workflow として実行する統一コマンドである。

I.8.2 オプション一覧

オプション 説明
--M 証明書を生成するサポート法 $M$ を指定する。既定値は現行論文採用値の 4096 である。
--block-size 最小値候補監査の block size を指定する。
--heartbeat-seconds 実行中 heartbeat の出力間隔を指定する。
--log-flush-seconds stage 別非同期 log の flush 間隔を指定する。
--internal-log-flush-seconds コマンド全体内部ログの flush 間隔を指定する。
--internal-log-fsync-seconds 内部ログの OS-level fsync 間隔を指定する。
--output-dir 全成果物の永続出力 root を指定する。
--workspace 互換用の明示 workspace path を指定する。
--results-dir 互換用の結果 ZIP ファイル出力ディレクトリを指定する。
--run-id 任意の一意な run ID を指定する。
--author-id 証明書の著者 ID を指定する。正式証明書では著者固有 ID を明示指定する。省略時は解決済みの作業者 UUID を著者 ID として用いる。
--operator-id 証明書生成・独立検証処理の作業者 ID を指定する。通常の単体試験では省略でき、未指定時は UUID v4 を一度だけ自動生成する。

I.8.3 既定値と出力先

 各オプションを省略した場合の既定値または既定動作は次である。

オプション 既定値または既定動作
--M 4096(現行論文採用値。全サポートMで証明書生成可能)
--block-size 4096
--heartbeat-seconds 60 秒
--log-flush-seconds 5.0 秒
--internal-log-flush-seconds 1.0 秒
--internal-log-fsync-seconds 60.0 秒
--output-dir 指定なし。Core実行package直下の runs/ および results/ を使用する。
--workspace 指定なし。プログラム版、$M$ および日時から一意な workspace を自動生成する。
--results-dir 指定なし。Core実行パッケージ直下の results/ を使用する。
--run-id プログラム版、$M$ および処理日時から自動生成する。
--author-id 指定なし。解決済みの作業者 UUID を著者 ID として使用する。
--operator-id 実行ごとに UUID v4 を一度だけ自動生成し、その実行内で生成・検証作業者 IDとして共用する。

 --output-dir を指定した場合、次の構成を生成する。

<output-dir>/runs/<run-id>/
<output-dir>/results/<run-id>_PASS.zip

 --run-id を省略した場合、プログラム版、$M$ および処理日時から
一意な run ID を自動生成する。

I.8.4 heartbeat ログ形式

 先頭項目へローカル日時を ISO 8601 形式で記録する。

[heartbeat] 2026-07-05T11:41:08+09:00 stage=generate elapsed_seconds=4725 child_pid=3188 running=True

 heartbeat ログでは、各行の出力時刻と UTC 差分を確認できる。
日時末尾の +09:00 は UTC との差分を示す。実行環境が UTC の場合は
+00:00となる。
 この表示仕様はコンソールおよび内部ログだけを対象とし、
有限状態 graph、候補監査、証明書内容、独立検証および
最終判定には影響しない。

I.9 検証プログラムの構成

 ここでは、検証プログラムのプログラム構造を示す。

I.9.1 概要

 検証プログラムは、統一コマンド、有限グラフ構築、有限還元、
完全監査、Layer 1 証明書、Layer 2 証明書、2層 core certificate、
独立検証および成果物保存の各処理からなる。

I.9.2 プログラム構造

ctv0100.py
  └─ LIC_core_manager.py
       ├─ finite graph construction
       ├─ finite reduction and audit
       ├─ Layer 1 certificate generation
       ├─ Layer 2 certificate generation
       ├─ LIC_independent_ch3_math.py
       │    └─ independent mathematical reconstruction
       └─ independent certificate verification and packaging

 生成系と独立検証系は、別のソースファイルとして分離する。
独立検証系の数学的再構成は LIC_independent_ch3_math.py に集約し、
生成系の graph 構築、上界計算、候補監査および構造値計算を
再利用しない。

I.9.3 処理フロー

 統一コマンドの処理は、次の 4 段階である。

Stage 1 : environment and source-integrity check
Stage 2 : selected-M finite-check certificate generation
Stage 3 : selected-M external independent verification
Stage 4 : result packaging

 Stage 2 および Stage 3 は、指定された対象 $M$ について実行される。

I.9.4 証明書生成系

 証明書生成系は、指定された $M$ について、有限グラフ、有限還元、
最小値候補監査および下位証拠の結果を読み取り、Layer 1、Layer 2 および
$M$ 識別付き2層 core certificate を生成する。

I.9.5 独立検証系

 独立検証系は、生成証明書の schema、入力 hash、数値、状態、
証明範囲および発行条件を再確認する。
 2層 core certificate verifier は、子証拠の論理相対パス、
ファイルサイズおよび SHA-256 も確認する。

 独立検証系では、数学的事実の再計算を
LIC_independent_ch3_math.py が担当する。
 同モジュールは、exact $R$-micrograph を独自に構築し、
derived logical $R$-graph の logical edgeを独立探索で列挙する。
さらに、全長別周期最小値上界、全奇数候補監査、復帰 cycle 詳細
および Layer 2 構造値を独立に再構成する。
 これにより、生成系と検証系が同一の graph builder、
上界計算関数または候補監査関数を共有することによる共通原因故障の
可能性を低減する。

I.10 リソースと版情報

 検証プログラムの提供版に関するバージョン情報等を以下に示す。

I.10.1 実行パッケージ

 Core 実行パッケージには、実行に必要な正味のファイルに加えて、
配布、監査、版管理および再現性確認のための README、manifest、
報告書等を収録している。
 ただし、これらの配布・管理資料を検証プログラムが起動時に必要とする
正味の対象ファイル群ではない。
 現行の統一プログラム構成において、実行開始前に同一ディレクトリへ
配置する必要がある正味のファイルは、次の 27 件だけである。

26 本の Python source
SOURCE_SHA256SUMS.txt

 Python ソースファイル以外で実行時に必要な既存ファイルは、
SOURCE_SHA256SUMS.txt だけである。
 この必要ファイル構成は、プログラム版および文書版の版番号とは
独立に扱う。後継版でソースファイル構成自体を変更しない限り、
同じ必要ファイル一覧を適用する。

I.10.2 実行時必要ファイルと配布資料の区別

 実行時必要ファイルの完全な一覧は、I.11 に示す。
全件を同一ディレクトリに配置し、ctv0100.py を起動する。
 事前にruns/、results/、証明書、log、JSON、CSV、Markdown、
成果物 ZIP ファイルまたは既存の出力ディレクトリを用意する必要はない。
これらは実行時に生成される。

 次のファイルまたは資料は、配布、監査、説明、版管理または
成果物保存には有用であるが、統一コマンドの実行入力としては
不要である。

  • README、操作説明書および仕様書
  • PACKAGE_MANIFEST.json、RESOURCE_MANIFEST.json 等の配布用 manifest
  • 配布 ZIP 全体の SHA256SUMS.txt
  • 変更報告、回帰試験報告および試験管理表
  • 既存の周期 lift 構造有限検査証明書、実行ログおよび結果 ZIP ファイル
  • 外部parameter file、catalog CSV および事前生成データ

I.10.3 実行時 source integrity と配布物の完全性確認

 SOURCE_SHA256SUMS.txt は実行時必要ファイルであり、
26 本の Core source を登録する。
 統一コマンドは起動時にこの一覧を読み、対象ソースファイルの存在
およびハッシュ値を確認する。
 SOURCE_SHA256SUMS.txt 自体を除く他の非 Python 既存ファイルは、
この source integrity 確認にも、証明書生成、独立検証または
パッケージ化にも必要としない。

 一方、配布用 Core package またはドキュメント統合版の
同一性・完全性は、配布物側のハッシュ値一覧と resource manifest により
確認する。
 これは配布物全体の監査規則であり、プログラム実行に必要な
入力ファイルの規則とは別である。

I.10.4 版情報

 本共通基準版の主基準 Core Program はX04a、文書版はD01である。
公開コマンド版は CTV 1.00 であり、内部プログラム版と文書版は
別に管理する。現時点の検証プログラム版はX04a-D01である。

 検証プログラムでは、通常の検査・検証状態値を
PASS、FAIL、WARNへ限定する。
 これとは別に、§3.5.2 の構造値固有の総合判断として、
Fixed、NOT_FIXED、UNVERIFIEDを用いる。
 周期 lift 構造有限検査証明書の schema は、構造値の期待値、
再構成値集合、確定判定および確定判定の独立検証を含む
LIC-APPENDIX-I-CORE-CERTIFICATE-v7 である。
また、証明書 metadata schema は CTV-CERTIFICATE-METADATA-v3 である。

 検証プログラムでは、独立 verifier の数学的再構成層として
LIC_independent_ch3_math.py を追加した。
 同モジュールは標準ライブラリだけを使用し、生成系の micrograph、
logical graph、上界、候補監査および Phase-B 構造の各実装を
import せず、本文定義から独立に再計算する。

 検証プログラムは、全サポート $M$ について、
周期 lift 構造有限検査証明書を構成する同一構造の2層 core certificate を
生成し、成果物名に対象 $M$ を含める。
 ctv0100.py の --M 既定値は4096であるが、これは現行論文の採用値を
実行するための既定値であり、証明書の生成を$M = 4096$へ
限定するものではない。

 プログラムの機能範囲は、指定 $M$ に対する周期 lift 構造有限検査証明書
と関連証拠の生成、独立検証および成果物保存に限定され、
論文固有の文書生成機能を含まない。

 本付録に掲載する$M=4096$の周期 lift 構造有限検査証明書は、
著者のローカル環境で、--M 4096、--author-idおよび--operator-idに
著者固有 ID を明示指定して実行した生成結果である。
 証明書 schema は LIC-APPENDIX-I-CORE-CERTIFICATE-v7 であり、
独立数学再構成、構造値の確定判定Fixedおよびその独立検証を含む。

I.11 実行時必要ファイル一覧

 現行の統一プログラム構成における実行時必要ファイルは、
以下の 26 本の Python ソースファイルと、その直後に示す
SOURCE_SHA256SUMS.txt の計 27 件である。
 全ファイルを ctv0100.py と同じディレクトリへ配置する。
Python ソースファイル以外の事前配置ファイルは SOURCE_SHA256SUMS.txt
のみである。

No. Python ソースファイル 役割
1 ctv0100.py 統一コマンド。環境確認、証明書生成、独立検証および成果物 ZIP ファイル生成を順に実行する。
2 ctv_environment_snapshot.py 実行環境 snapshot を取得する。
3 ctv_internal_console_log.py コマンド全体の内部コンソールログを永続化する。
4 LIC_appendix_i_core_certificate.py 指定 $M$ の $M$ 識別付き2層 core certificate を生成する。
5 LIC_appendix_i_core_certificate_verifier.py 指定 $M$ の $M$ 識別付き2層 core certificate を独立検証する。
6 LIC_certificate_logical_paths.py 証明書が参照する論理相対パスを管理する。
7 LIC_certificate_metadata.py 証明書の著者 ID、作業者 ID、作成・検証日時等を管理する。
8 LIC_complete_cycle_classification.py Layer 1 の正整数周期 lift 完全分類証明書を生成する。
9 LIC_complete_cycle_classification_verifier.py Layer 1 証明書を独立検証する。
10 LIC_constants.py Core 共通定数を定義する。
11 LIC_independent_ch3_math.py 本体数学実装を再利用せず、micrograph、logical edge、上界、全候補監査および構造値を独立再構成する。
12 LIC_core_manager.py Core 内部コマンドの管理を行う。
13 LIC_cycle_minimum_audit.py 周期最小値候補を完全監査する。
14 LIC_cycle_minimum_audit_verifier.py 周期最小値候補監査を独立数学再構成結果と照合する。
15 LIC_cycle_minimum_bound.py サイクル長毎の周期最小値上界を計算する。
16 LIC_finite_lp_cycle_bridge.py finite circulation と simple cycle の対応証拠を生成する。
17 LIC_finite_lp_cycle_bridge_verifier.py finite circulation bridge を独立数学再構成結果と照合する。
18 LIC_phase_b_structure.py 全 cycle 長に対する目的値窓構造の証拠を生成する。
19 LIC_phase_b_structure_verifier.py 目的値窓構造をverifier側の独立定義と照合する。
20 LIC_r_logical_graph.py 生成系でderived logical $R$-graphを構成する。
21 LIC_r_micrograph.py 生成系でexact $R$-micrographを構成する。
22 LIC_r_transition.py 奇数コラッツ遷移に対する $R()$ 適用での厳密処理を提供する。
23 LIC_status.py 判定用状態値PASS、FAIL、WARNを一元定義する。
24 LIC_structural_lambda_certificate.py Layer 2 の構造値証明書を生成する。
25 LIC_structural_lambda_certificate_verifier.py Layer 2証明書を独立再構成した構造値と照合する。
26 LIC_version.py プログラムおよびパッケージのバージョンを定義する。

 Python ソースファイル以外で実行時に必要なファイルは、次の 1 件である。

No. required non-Python file 役割
27 SOURCE_SHA256SUMS.txt 26 本の Python ソースファイルのファイル名とハッシュ値を登録し、統一コマンド起動時の source integrity 確認に用いる。

 実行後に作成される__pycache__/、runs/、results/、
証明書 JSON/TXT/Markdown、監査 CSV、ログ、サマリー、
ハッシュ値ファイルおよび結果 ZIP ファイルは生成物であり、
実行開始前の必要ファイルではない。
 また、配布用 README、manifest、報告書および全体ハッシュ値一覧も
実行開始条件には含まれない。

 この一覧は、版番号の文字列そのものではなく、現行統一プログラムの
ソースファイル構造に基づく。
 将来、ソースファイルの追加、削除、改名または起動時入力仕様の変更を
行う場合に限り、本一覧を明示的に改訂する。

I.12 検証プログラムのソースコード

 本節には、検証プログラムの実行時必要ファイルを構成する、
Python ソースコードの全体を掲載する。
 SOURCE_SHA256SUMS.txt はソースコードではなく、
source integrity 確認用ファイルであるため、前節 I.11 に
必要ファイルとして記載し、本節のコード掲載対象には含めない。

I.12.1 ctv0100.py

#!/usr/bin/env python3
"""One-command execution interface for Collatz Transition Verification.

Source metadata:
    File name: ctv0100.py
    Program version: X04a
    Source file version: 1.1.1
    Created: 2026-07-29 23:55:10 JST
    Last updated: 2026-08-02 16:32:00 JST

Function summary:
    Runs the public CTV 1.00 workflow: environment and source-integrity checks,
    selected-modulus certificate generation, independent verification, and result
    packaging.

Command interface:
    Command syntax:
        python -u ctv0100.py [options]

    Options:
        -h, --help
            Shows the command help and exits.
        --M <value>
            Selects the finite-state modulus. Supported values are 1024, 2048,
            4096, 8192, 16384, 32768, and 65536. Default: 4096.
        --block-size <integer>
            Sets the minimum-candidate audit block size. Default: 4096.
        --heartbeat-seconds <integer>
            Sets the stage heartbeat interval in seconds. Default: 60.
        --log-flush-seconds <seconds>
            Sets the periodic flush interval for stage-specific asynchronous logs.
            Default: 5.0.
        --internal-log-flush-seconds <seconds>
            Sets the flush interval for the mandatory whole-command internal log.
            Default: 1.0.
        --internal-log-fsync-seconds <seconds>
            Sets the OS-level fsync interval for the mandatory internal log.
            Default: 60.0.
        --output-dir <path>
            Sets the persistent output root. The command creates runs/<run-id>
            and results below this directory.
        --workspace <path>
            Sets a legacy explicit unique workspace path.
        --results-dir <path>
            Sets a legacy explicit PASS/FAILED ZIP output directory.
        --run-id <identifier>
            Sets an optional unique run identifier.
        --author-id <UUID>
            Records the supplied certificate-author UUID. When omitted, the
            resolved operator UUID is used as the certificate-author UUID.
        --operator-id <UUID>
            Records the supplied operator UUID in generation and verification
            evidence. When omitted, one UUID v4 is generated for the run.

    Typical usage:
        python -u ctv0100.py --M 4096 \
            --author-id "623203b4-e7d8-4d4e-ad02-accf6cd2af21" \
            --operator-id "623203b4-e7d8-4d4e-ad02-accf6cd2af21"
        where "623203b4-e7d8-4d4e-ad02-accf6cd2af21" is an example identifier.

    Exit status:
        0
            All four stages completed successfully.
        Non-zero
            The command stopped after an environment, source-integrity,
            generation, independent-verification, or packaging failure.

    Main outputs:
        - Machine-readable and human-readable two-layer finite-check certificates.
        - Independent-verification summary and child evidence.
        - Mandatory whole-command internal console log and metadata.
        - PASS or diagnostic result ZIP archive and SHA-256 sidecar.

Remarks:
    This is the public driver command. It uses only the Python standard library
    directly and delegates mathematical certificate work to the Core manager.
    --output-dir cannot be combined with --workspace or --results-dir. Legacy
    workspace and result-directory options are retained for compatibility.
    Individual source-file versioning starts with this metadata revision. Earlier
    file-level changes are retained in package history but are not reconstructed as
    separate source-file versions.

Change history:
    - 1.1.1 / X04a / 2026-08-02 16:32:00 JST
      Updated X04a Program-membership metadata; executable logic is unchanged.
    - 1.1.0 / X03f / 2026-08-01 23:28:33 JST
      Added user-selectable certificate author identity via --author-id, separated author and operator identities, and propagated both identities through generation and verification.
    - 1.0.0 / X03e / 2026-08-01 05:17:15 JST
      Added the standardized English source metadata header, documented every
      public command option, added a typical --M/--operator-id usage example, and
      normalized the public UI status text to "public driver interface".

The command performs, in order:
    1. common environment snapshot and source-integrity checks;
    2. selected-M two-layer finite-check certificate generation;
    3. external independent verification of that certificate;
    4. PASS result ZIP and SHA-256 creation.

On failure it stops immediately and creates a diagnostic ZIP when possible.
A mandatory whole-command internal console log is written inside the workspace
with line-boundary flushes, periodic fsync, SHA-256 metadata, and result-ZIP
inclusion. Stage-specific child logging remains asynchronous. Only Python's
standard library is used by this interface. No shell or external tee is required.
"""
from __future__ import annotations

import argparse
import hashlib
import json
import os
import platform
import queue
import shutil
import subprocess
import sys
import threading
import time
import zipfile
from datetime import datetime
from pathlib import Path
from typing import Iterable

from ctv_environment_snapshot import collect_environment_snapshot, format_snapshot_lines
from ctv_internal_console_log import InternalConsoleLogger
from LIC_version import PACKAGE_LABEL
from LIC_status import STATUS_FAIL, STATUS_PASS, STATUS_WARN
from LIC_certificate_metadata import (
    canonical_uuid,
    resolve_author_identity,
    resolve_operator_identity,
)

PUBLIC_NAME = "Collatz Transition Verification"
PUBLIC_ABBREVIATION = "CTV"
PUBLIC_UI_VERSION = "1.00"
PUBLIC_ENTRY_POINT = "ctv0100.py"
PUBLIC_UI_STATUS = "public driver interface"
SUPPORTED_M = (1024, 2048, 4096, 8192, 16384, 32768, 65536)
EXPECTED_STATUS = STATUS_PASS
ROOT = Path(__file__).resolve().parent
MANAGER = ROOT / "LIC_core_manager.py"
SOURCE_HASHES = ROOT / "SOURCE_SHA256SUMS.txt"


class AsyncTeeSink:
    """Asynchronous console/file sink for child-process output.

    The child stdout reader and the console/log writer are separated from the
    orchestration thread.  File flushes are periodic rather than per line.
    This keeps output handling from delaying a chatty child process while
    retaining bounded log-loss exposure on an abrupt host termination.
    """

    def __init__(
        self,
        log_stream,
        *,
        file_flush_seconds: float = 5.0,
        batch_chars: int = 65536,
        queue_capacity: int = 4096,
    ) -> None:
        self._log = log_stream
        self._file_flush_seconds = max(0.1, float(file_flush_seconds))
        self._batch_chars = max(1024, int(batch_chars))
        self._queue: queue.Queue[tuple[str, str | None, threading.Event | None]] = (
            queue.Queue(maxsize=max(16, int(queue_capacity)))
        )
        self._error: BaseException | None = None
        self._closed = False
        self._total_chars = 0
        self._input_chunks = 0
        self._output_batches = 0
        self._file_flush_count = 0
        self._thread = threading.Thread(
            target=self._worker, name="ctv-async-tee-writer", daemon=True
        )
        self._thread.start()

    def _raise_if_failed(self) -> None:
        if self._error is not None:
            raise RuntimeError(f"asynchronous log writer failed: {self._error}")

    def write(self, text: str) -> None:
        if not text:
            return
        if self._closed:
            raise RuntimeError("write requested after asynchronous log sink close")
        self._raise_if_failed()
        self._queue.put(("data", text, None))

    def flush(self) -> None:
        if self._closed:
            return
        self._raise_if_failed()
        done = threading.Event()
        self._queue.put(("flush", None, done))
        if not done.wait(timeout=30.0):
            self._raise_if_failed()
            raise RuntimeError("asynchronous log writer flush timed out")
        self._raise_if_failed()

    def close(self) -> None:
        if self._closed:
            return
        done = threading.Event()
        self._queue.put(("close", None, done))
        if not done.wait(timeout=30.0):
            self._raise_if_failed()
            raise RuntimeError("asynchronous log writer close timed out")
        self._thread.join(timeout=30.0)
        if self._thread.is_alive():
            raise RuntimeError("asynchronous log writer thread did not terminate")
        self._closed = True
        self._raise_if_failed()

    def stats(self) -> dict[str, int | float]:
        if not self._closed:
            raise RuntimeError("asynchronous log sink stats requested before close")
        return {
            "total_output_chars": self._total_chars,
            "input_chunks": self._input_chunks,
            "output_batches": self._output_batches,
            "file_flush_count": self._file_flush_count,
            "file_flush_seconds": self._file_flush_seconds,
            "batch_chars": self._batch_chars,
        }

    def _worker(self) -> None:
        pending: list[str] = []
        pending_chars = 0
        last_output = time.monotonic()
        last_file_flush = last_output
        dirty = False

        def emit(*, force_file_flush: bool = False) -> None:
            nonlocal pending, pending_chars, last_output, last_file_flush, dirty
            if pending:
                data = "".join(pending)
                sys.stdout.write(data)
                self._log.write(data)
                self._output_batches += 1
                dirty = True
                pending = []
                pending_chars = 0
                last_output = time.monotonic()
            now = time.monotonic()
            # Console visibility is kept prompt; disk flush is intentionally
            # periodic instead of occurring for every output line.
            sys.stdout.flush()
            if dirty and (
                force_file_flush or now - last_file_flush >= self._file_flush_seconds
            ):
                self._log.flush()
                self._file_flush_count += 1
                last_file_flush = now
                dirty = False

        try:
            while True:
                try:
                    kind, text, done = self._queue.get(timeout=0.25)
                except queue.Empty:
                    kind, text, done = "tick", None, None

                if kind == "data":
                    assert text is not None
                    pending.append(text)
                    pending_chars += len(text)
                    self._total_chars += len(text)
                    self._input_chunks += 1
                    if pending_chars >= self._batch_chars:
                        emit()
                elif kind == "flush":
                    emit(force_file_flush=True)
                    assert done is not None
                    done.set()
                elif kind == "close":
                    emit(force_file_flush=True)
                    assert done is not None
                    done.set()
                    return
                elif kind == "tick":
                    now = time.monotonic()
                    if pending and now - last_output >= 0.25:
                        emit()
                    elif dirty and now - last_file_flush >= self._file_flush_seconds:
                        self._log.flush()
                        last_file_flush = now
                        dirty = False
        except BaseException as exc:  # preserve the first writer failure
            self._error = exc
            # Release a waiting flush/close caller if possible.
            try:
                if 'done' in locals() and done is not None:
                    done.set()
            except Exception:
                pass


def timestamp() -> str:
    return datetime.now().strftime("%Y%m%d_%H%M%S")


def iso_now() -> str:
    return datetime.now().astimezone().isoformat(timespec="seconds")


def format_elapsed_seconds(seconds: float) -> str:
    """Format elapsed seconds as HH:MM:SS.mmm for operator scheduling."""
    total_milliseconds = max(0, int(round(float(seconds) * 1000.0)))
    hours, remainder = divmod(total_milliseconds, 3_600_000)
    minutes, remainder = divmod(remainder, 60_000)
    whole_seconds, milliseconds = divmod(remainder, 1000)
    return f"{hours:02d}:{minutes:02d}:{whole_seconds:02d}.{milliseconds:03d}"


def build_command_timing(started_at: str, start_monotonic: float) -> dict:
    finished_at = iso_now()
    elapsed_seconds = time.monotonic() - start_monotonic
    return {
        "command_started_at": started_at,
        "command_finished_at": finished_at,
        "command_elapsed_seconds": round(elapsed_seconds, 3),
        "command_elapsed_human": format_elapsed_seconds(elapsed_seconds),
    }


def print_command_start(started_at: str) -> None:
    print("=" * 72, flush=True)
    print("ONE-COMMAND TIMING", flush=True)
    print("=" * 72, flush=True)
    print(f"command_started_at      : {started_at}", flush=True)
    print("=" * 72, flush=True)


def print_command_finish(timing: dict, *, stream=None) -> None:
    if stream is None:
        stream = sys.stdout
    print(f"command_started_at      : {timing['command_started_at']}", file=stream, flush=True)
    print(f"command_finished_at     : {timing['command_finished_at']}", file=stream, flush=True)
    print(
        f"command_elapsed         : {timing['command_elapsed_human']} "
        f"({timing['command_elapsed_seconds']:.3f} seconds)",
        file=stream,
        flush=True,
    )


def save_command_timing(
    summary: dict,
    workspace: Path,
    timing: dict,
) -> None:
    summary["command_timing"] = timing
    summary["command_started_at"] = timing["command_started_at"]
    summary["command_finished_at"] = timing["command_finished_at"]
    summary["command_elapsed_seconds"] = timing["command_elapsed_seconds"]
    summary["command_elapsed_human"] = timing["command_elapsed_human"]
    summary["finished_at"] = timing["command_finished_at"]
    write_json(workspace / "logs" / "05_command_timing.json", timing)
    write_summary(workspace, summary)


def sha256_file(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as stream:
        for block in iter(lambda: stream.read(1024 * 1024), b""):
            digest.update(block)
    return digest.hexdigest()


def write_json(path: Path, value: dict) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(
        json.dumps(value, ensure_ascii=False, indent=2, sort_keys=True) + "\n",
        encoding="utf-8",
        newline="\n",
    )


def write_environment_snapshot(path: Path, snapshot: dict) -> None:
    write_json(path, snapshot)


def environment_snapshot_text(snapshot: dict) -> str:
    lines = [
        "=" * 72,
        "COMMON ENVIRONMENT SNAPSHOT",
        "=" * 72,
        *format_snapshot_lines(snapshot),
    ]
    for error in snapshot.get("collection_errors", []):
        lines.append(f"environment_collection_warning: {error}")
    lines.append("=" * 72)
    return "\n".join(lines) + "\n"


def print_environment_snapshot(snapshot: dict) -> None:
    print(environment_snapshot_text(snapshot), end="", flush=True)


def write_environment_snapshot_text(path: Path, snapshot: dict) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(environment_snapshot_text(snapshot), encoding="utf-8", newline="\n")


def load_json(path: Path) -> dict:
    try:
        value = json.loads(path.read_text(encoding="utf-8"))
    except Exception as exc:
        raise RuntimeError(f"JSON read failed: {path}: {exc}") from exc
    if not isinstance(value, dict):
        raise RuntimeError(f"JSON root is not an object: {path}")
    return value


def command_text(command: Iterable[str]) -> str:
    return subprocess.list2cmdline(list(command))


def verify_source_integrity() -> dict:
    if not SOURCE_HASHES.is_file():
        raise RuntimeError(f"missing source hash file: {SOURCE_HASHES.name}")
    checked = 0
    errors: list[str] = []
    for raw_line in SOURCE_HASHES.read_text(encoding="ascii").splitlines():
        line = raw_line.strip()
        if not line or line.startswith("#"):
            continue
        try:
            expected, relative = line.split(None, 1)
        except ValueError:
            errors.append(f"invalid hash line: {line}")
            continue
        relative = relative.strip().lstrip("*")
        path = ROOT / relative
        if not path.is_file():
            errors.append(f"missing source file: {relative}")
            continue
        actual = sha256_file(path)
        if actual.lower() != expected.lower():
            errors.append(
                f"SHA-256 mismatch: {relative}: expected={expected} actual={actual}"
            )
        checked += 1
    manifest_sources = set()
    for raw_line in SOURCE_HASHES.read_text(encoding="ascii").splitlines():
        line = raw_line.strip()
        if not line or line.startswith("#"):
            continue
        _expected, relative = line.split(None, 1)
        manifest_sources.add(relative.strip().lstrip("*"))
    discovered_sources = {p.name for p in ROOT.glob("*.py") if p.is_file()}
    if manifest_sources != discovered_sources:
        missing_from_manifest = sorted(discovered_sources - manifest_sources)
        missing_from_package = sorted(manifest_sources - discovered_sources)
        if missing_from_manifest:
            errors.append("unregistered Python source: " + ", ".join(missing_from_manifest))
        if missing_from_package:
            errors.append("manifest source missing from package: " + ", ".join(missing_from_package))
    if errors:
        raise RuntimeError("source integrity failure:\n" + "\n".join(errors))
    return {
        "status": "PASS",
        "checked_source_files": checked,
        "all_python_sources_covered": True,
    }


def check_environment(start_snapshot: dict) -> dict:
    if not MANAGER.is_file():
        raise RuntimeError(f"missing manager: {MANAGER}")
    integrity = verify_source_integrity()
    try:
        import numpy  # type: ignore
        import scipy  # type: ignore
    except Exception as exc:
        raise RuntimeError(
            f"required core package import failed: {exc}; "
            "install numpy and scipy before execution"
        ) from exc

    completed = subprocess.run(
        [sys.executable, str(MANAGER), "--help"],
        cwd=ROOT,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        text=True,
        encoding="utf-8",
        errors="replace",
    )
    if completed.returncode != 0:
        raise RuntimeError(f"manager help check failed: {completed.stdout}")
    manager_help = completed.stdout
    entry_points = {
        subcommand: subcommand in manager_help
        for subcommand in (
            "appendix-i-core-certificate",
            "verify-appendix-i-core-certificate",
        )
    }
    missing_entry_points = [name for name, found in entry_points.items() if not found]
    if missing_entry_points:
        raise RuntimeError(
            "command entry point unavailable: " + ", ".join(missing_entry_points)
        )

    disk = shutil.disk_usage(ROOT)
    return {
        "status": "PASS",
        "environment_snapshot_schema": start_snapshot.get("schema_id"),
        "environment_snapshot_status": start_snapshot.get("status"),
        "environment_snapshot": start_snapshot,
        "public_name": PUBLIC_NAME,
        "public_abbreviation": PUBLIC_ABBREVIATION,
        "public_ui_version": PUBLIC_UI_VERSION,
        "public_ui_status": PUBLIC_UI_STATUS,
        "public_entry_point": PUBLIC_ENTRY_POINT,
        "internal_engine": PACKAGE_LABEL,
        "package_label": PACKAGE_LABEL,
        "python_version": sys.version,
        "python_executable": sys.executable,
        "platform": platform.platform(),
        "package_directory": str(ROOT),
        "free_disk_bytes": disk.free,
        "source_integrity": integrity,
        "numpy_version": numpy.__version__,
        "scipy_version": scipy.__version__,
        "entry_points": entry_points,
    }


def run_logged(
    command: list[str],
    log_path: Path,
    *,
    stage: str,
    heartbeat_seconds: int,
    log_flush_seconds: float,
) -> tuple[int, float, dict[str, int | float]]:
    log_path.parent.mkdir(parents=True, exist_ok=True)
    start = time.monotonic()
    header = [
        f"public_name={PUBLIC_NAME}",
        f"public_ui_version={PUBLIC_UI_VERSION}",
        f"public_ui_status={PUBLIC_UI_STATUS}",
        f"internal_engine={PACKAGE_LABEL}",
        f"stage={stage}",
        f"python={sys.executable}",
        f"platform={platform.platform()}",
        f"working_directory={ROOT}",
        f"command={command_text(command)}",
        f"started_at={iso_now()}",
        "",
    ]
    for line in header:
        print(line, flush=True)

    with log_path.open("w", encoding="utf-8", newline="\n", buffering=1024 * 1024) as log:
        for line in header:
            log.write(line + "\n")
        log.flush()

        process = subprocess.Popen(
            command,
            cwd=ROOT,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            text=True,
            encoding="utf-8",
            errors="replace",
            bufsize=1,
        )
        assert process.stdout is not None
        output_queue: queue.Queue[str | None] = queue.Queue(maxsize=4096)
        sink = AsyncTeeSink(log, file_flush_seconds=log_flush_seconds)

        def reader() -> None:
            try:
                for output_line in process.stdout:
                    output_queue.put(output_line)
            finally:
                output_queue.put(None)

        thread = threading.Thread(
            target=reader, name=f"ctv-{stage}-stdout-reader", daemon=True
        )
        thread.start()
        last_heartbeat = start
        closed = False
        return_code = 1
        try:
            while not closed:
                try:
                    item = output_queue.get(timeout=1.0)
                except queue.Empty:
                    item = ""
                if item is None:
                    closed = True
                elif item:
                    sink.write(item)

                now = time.monotonic()
                if heartbeat_seconds > 0 and now - last_heartbeat >= heartbeat_seconds:
                    message = (
                        f"[heartbeat] {iso_now()} stage={stage} "
                        f"elapsed_seconds={now - start:.0f} "
                        f"child_pid={process.pid} running={process.poll() is None}"
                    )
                    sink.write(message + "\n")
                    # A heartbeat is also a durability boundary for the log.
                    sink.flush()
                    last_heartbeat = now
            return_code = process.wait()
        except KeyboardInterrupt:
            sink.write("INTERRUPTED: terminating child process...\n")
            sink.flush()
            process.terminate()
            try:
                process.wait(timeout=10)
            except subprocess.TimeoutExpired:
                process.kill()
            return_code = 130
        finally:
            try:
                process.stdout.close()
            except Exception:
                pass

        elapsed = time.monotonic() - start
        footer = [
            "",
            f"finished_at={iso_now()}",
            f"elapsed_seconds={elapsed:.3f}",
            f"exit_code={return_code}",
        ]
        sink.write("\n".join(footer) + "\n")
        sink.close()
        io_stats = sink.stats()
    return return_code, elapsed, io_stats


def _core_certificate_stem(modulus: int) -> str:
    return f"appendix_i_core_certificate_M{int(modulus)}"


def validate_generation(run_dir: Path, modulus: int) -> dict:
    stem = _core_certificate_stem(modulus)
    certificate = load_json(run_dir / f"{stem}.json")
    required = {
        "package_label": PACKAGE_LABEL,
        "M": modulus,
        "b": modulus.bit_length() - 1,
        "maximum_simple_logical_cycle_length": modulus // 2,
        "nontrivial_positive_integer_periodic_lifts_found": 0,
        "trivial_1_loop_confirmed": True,
        "layer_1_independent_verify": "PASS",
        "layer_2_independent_verify": "PASS",
        "valid_periodic_lift_structural_lambda_x": "1",
        "core_certificate_issued": True,
        "proof_uses_underlying_edge_deletion": False,
        "unrestricted_infinite_empirical_flow_lower_bound_claimed": False,
        "status": EXPECTED_STATUS,
    }
    mismatches = {
        key: {"expected": expected, "actual": certificate.get(key)}
        for key, expected in required.items()
        if certificate.get(key) != expected
    }
    required_files = [
        run_dir / f"{stem}.json",
        run_dir / f"{stem}.txt",
        run_dir / f"{stem}_report.md",
        run_dir / f"{stem}.sha256",
    ]
    missing = [str(path) for path in required_files if not path.is_file()]
    if mismatches or missing:
        raise RuntimeError(
            "finite-check certificate generation validation failed:\n"
            + json.dumps({"mismatches": mismatches, "missing": missing}, ensure_ascii=False, indent=2)
        )
    return certificate


def validate_verification(run_dir: Path, modulus: int) -> dict:
    stem = _core_certificate_stem(modulus)
    summary = load_json(run_dir / f"{stem}_verify_summary.json")
    if summary.get("package_label") != PACKAGE_LABEL:
        raise RuntimeError("verification package_label mismatch")
    if summary.get("M") != modulus:
        raise RuntimeError("verification M mismatch")
    if summary.get("verification_status") != STATUS_PASS:
        raise RuntimeError("verification_status is not PASS")
    if summary.get("overall_status") != EXPECTED_STATUS:
        raise RuntimeError("verification overall_status mismatch")
    checks = summary.get("checks")
    if not isinstance(checks, dict) or not checks or not all(v is True for v in checks.values()):
        bad = {} if not isinstance(checks, dict) else {
            key: value for key, value in checks.items() if value is not True
        }
        raise RuntimeError(
            "verification checks contain non-true entries:\n"
            + json.dumps(bad, ensure_ascii=False, indent=2)
        )
    required_files = [
        run_dir / f"{stem}.json",
        run_dir / f"{stem}.txt",
        run_dir / f"{stem}_verify_summary.json",
        run_dir / f"{stem}.sha256",
    ]
    missing = [str(path) for path in required_files if not path.is_file()]
    if missing:
        raise RuntimeError("verified certificate artifacts missing: " + json.dumps(missing))
    return summary


def write_summary(workspace: Path, summary: dict) -> None:
    write_json(workspace / "execution_summary.json", summary)
    stages = summary.get("stages", {})
    lines = [
        f"# {PUBLIC_NAME} {PUBLIC_UI_VERSION} / {PACKAGE_LABEL} M={summary.get('M')} execution summary",
        "",
        f"- status: `{summary.get('status')}`",
        f"- started_at: `{summary.get('started_at')}`",
        f"- finished_at: `{summary.get('finished_at', '')}`",
        f"- workspace: `{summary.get('workspace')}`",
        f"- output mode: `{summary.get('output', {}).get('mode', '')}`",
        f"- output root: `{summary.get('output', {}).get('output_root', '')}`",
        f"- results directory: `{summary.get('results_directory', '')}`",
    ]
    command_timing = summary.get("command_timing", {})
    if command_timing:
        lines.extend([
            "",
            "## Command timing",
            "",
            f"- command_started_at: `{command_timing.get('command_started_at', '')}`",
            f"- command_finished_at: `{command_timing.get('command_finished_at', '')}`",
            f"- command_elapsed: `{command_timing.get('command_elapsed_human', '')}`",
            f"- command_elapsed_seconds: `{command_timing.get('command_elapsed_seconds', '')}`",
        ])
    lines.extend([
        "",
        "## Stages",
        "",
    ])
    for name in ("check", "generate", "verify", "package"):
        stage = stages.get(name, {})
        lines.append(
            f"- {name}: status=`{stage.get('status', 'NOT_RUN')}`, "
            f"exit_code=`{stage.get('exit_code', '')}`, "
            f"elapsed_seconds=`{stage.get('elapsed_seconds', '')}`"
        )
    environment_start = summary.get("environment_start", {})
    if environment_start:
        env = environment_start.get("execution_environment", {})
        osinfo = environment_start.get("operating_system", {})
        py = environment_start.get("python", {})
        cpu = environment_start.get("cpu", {})
        memory = environment_start.get("memory", {})
        lines.extend([
            "",
            "## Environment",
            "",
            f"- snapshot schema: `{environment_start.get('schema_id', '')}`",
            f"- environment kind: `{env.get('kind', '')}`",
            f"- platform: `{osinfo.get('platform', '')}`",
            f"- Python: `{py.get('version_info', '')}`",
            f"- logical CPUs visible: `{cpu.get('logical_cpus_visible', '')}`",
            f"- effective CPU limit: `{cpu.get('effective_cpu_limit', '')}`",
            f"- physical memory bytes: `{memory.get('physical_total_bytes', '')}`",
            f"- effective memory limit bytes: `{memory.get('effective_limit_bytes', '')}`",
            f"- start snapshot JSON: `{summary.get('environment_start_file', '')}`",
            f"- start snapshot text: `{summary.get('environment_start_text_file', '')}`",
        ])
    if summary.get("error"):
        lines.extend(["", "## Error", "", "```text", str(summary["error"]), "```"])
    (workspace / "execution_summary.md").write_text(
        "\n".join(lines) + "\n", encoding="utf-8", newline="\n"
    )


def zip_tree(source_dir: Path, archive: Path, prefix: str) -> None:
    archive.parent.mkdir(parents=True, exist_ok=True)
    with zipfile.ZipFile(
        archive,
        mode="w",
        compression=zipfile.ZIP_DEFLATED,
        compresslevel=9,
        allowZip64=True,
    ) as output:
        for path in sorted(source_dir.rglob("*")):
            if path.is_file():
                output.write(path, str(Path(prefix) / path.relative_to(source_dir)))


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description=(
            "Collatz Transition Verification one-command workflow: check, generate, independently verify, "
            "and package the result"
        )
    )
    parser.add_argument(
        "--M",
        type=int,
        choices=SUPPORTED_M,
        default=4096,
        help="finite-state modulus M (default: 4096; every supported M issues its own certificate)",
    )
    parser.add_argument("--block-size", type=int, default=4096)
    parser.add_argument("--heartbeat-seconds", type=int, default=60)
    parser.add_argument(
        "--log-flush-seconds",
        type=float,
        default=5.0,
        help="periodic file-log flush interval for stage-specific asynchronous logs",
    )
    parser.add_argument(
        "--internal-log-flush-seconds",
        type=float,
        default=1.0,
        help="flush interval for the mandatory whole-command internal console log",
    )
    parser.add_argument(
        "--internal-log-fsync-seconds",
        type=float,
        default=60.0,
        help="OS-level fsync interval for the mandatory internal console log",
    )
    parser.add_argument(
        "--output-dir",
        help=(
            "persistent output root for all run artifacts; creates "
            "<output-dir>/runs/<run-id> and <output-dir>/results. "
            "Use an absolute Google Drive mount path in Google Colab."
        ),
    )
    parser.add_argument("--workspace", help="legacy explicit unique workspace path")
    parser.add_argument("--results-dir", help="legacy explicit PASS/FAILED ZIP output directory")
    parser.add_argument("--run-id", help="optional unique run identifier")
    parser.add_argument(
        "--author-id",
        type=canonical_uuid,
        help=(
            "optional certificate-author UUID/GUID; when omitted, the resolved "
            "operator UUID is used as the certificate-author UUID"
        ),
    )
    parser.add_argument(
        "--operator-id",
        type=canonical_uuid,
        help=(
            "optional run-scoped operator UUID/GUID; when omitted, one UUID v4 is "
            "generated once and shared by all generation and verification stages"
        ),
    )
    args = parser.parse_args()
    if args.output_dir and (args.workspace or args.results_dir):
        parser.error("--output-dir cannot be combined with --workspace or --results-dir")
    return args



_DYNAMIC_PACKAGE_PATHS = {
    Path("execution_console.log"),
    Path("execution_console.log.sha256"),
    Path("execution_summary.json"),
    Path("execution_summary.md"),
    Path("logs/05_command_timing.json"),
    Path("logs/06_internal_console_log.json"),
}


def _write_workspace_zip_static_entries(
    output: zipfile.ZipFile,
    source_dir: Path,
    prefix: str,
) -> None:
    """Write all stable workspace files before the internal log is finalized."""
    for item in sorted(source_dir.rglob("*")):
        if not item.is_file():
            continue
        relative = item.relative_to(source_dir)
        if relative in _DYNAMIC_PACKAGE_PATHS:
            continue
        output.write(item, str(Path(prefix) / relative))


def _write_workspace_zip_dynamic_entries(
    output: zipfile.ZipFile,
    source_dir: Path,
    prefix: str,
) -> None:
    """Write finalized log, timing, and summary records last."""
    for relative in sorted(_DYNAMIC_PACKAGE_PATHS, key=lambda value: str(value)):
        item = source_dir / relative
        if item.is_file():
            output.write(item, str(Path(prefix) / relative))


def _absolute_cli_path(value: str, *, relative_base: Path) -> Path:
    """Expand a CLI path and make relative paths deterministic."""
    path = Path(value).expanduser()
    if not path.is_absolute():
        path = relative_base / path
    return path.absolute()


def _preflight_output_root(output_root: Path) -> dict[str, object]:
    """Create and verify the persistent output root before a long run starts."""
    output_root.mkdir(parents=True, exist_ok=True)
    if not output_root.is_dir():
        raise RuntimeError(f"output directory is not a directory: {output_root}")
    probe = output_root / f".ctv_output_preflight_{os.getpid()}_{time.time_ns()}.tmp"
    payload = f"CTV output preflight {iso_now()}\n".encode("utf-8")
    try:
        with probe.open("xb") as stream:
            stream.write(payload)
            stream.flush()
            os.fsync(stream.fileno())
        observed = probe.read_bytes()
        if observed != payload:
            raise RuntimeError("output directory preflight read-back mismatch")
    finally:
        try:
            probe.unlink()
        except FileNotFoundError:
            pass
    try:
        disk = shutil.disk_usage(output_root)
        disk_info = {
            "total_bytes": disk.total,
            "used_bytes": disk.used,
            "free_bytes": disk.free,
        }
    except Exception as exc:
        disk_info = {"collection_error": str(exc)}
    return {
        "status": "PASS",
        "path": str(output_root),
        "write_readback": True,
        "file_fsync": True,
        "disk": disk_info,
        "checked_at": iso_now(),
    }


def _finalize_internal_console_log(
    logger: InternalConsoleLogger,
    *,
    original_stdout,
    original_stderr,
    workspace: Path,
    logs_dir: Path,
    summary: dict,
) -> dict:
    """Close, hash, and register the mandatory whole-command internal log."""
    try:
        logger.durability_boundary()
    finally:
        sys.stdout = original_stdout
        sys.stderr = original_stderr
    metadata = logger.close()
    log_path = workspace / "execution_console.log"
    hash_path = workspace / "execution_console.log.sha256"
    if log_path.is_file():
        hash_path.write_text(
            f"{metadata.get('sha256', '')}  {log_path.name}\n",
            encoding="ascii",
            newline="\n",
        )
    metadata["sha256_file"] = str(hash_path)
    metadata_path = logs_dir / "06_internal_console_log.json"
    metadata["metadata_file"] = str(metadata_path)
    write_json(metadata_path, metadata)
    summary["internal_console_log"] = metadata
    summary.setdefault("io", {})["internal_console_log_status"] = metadata.get("status")
    summary["io"]["internal_console_log_path"] = str(log_path)
    summary["io"]["internal_console_log_sha256_file"] = str(hash_path)
    if metadata.get("status") != "COMPLETE" and summary.get("status") == STATUS_PASS:
        summary["status"] = STATUS_WARN
        summary["warning_code"] = "LOGGING_ANOMALY"
    write_summary(workspace, summary)
    return metadata

def main() -> int:
    command_start_monotonic = time.monotonic()
    command_started_at = iso_now()
    try:
        args = parse_args()
    except SystemExit as exc:
        timing = build_command_timing(command_started_at, command_start_monotonic)
        print("=" * 72, file=sys.stderr, flush=True)
        print("COMMAND FINISHED BEFORE WORKFLOW START", file=sys.stderr, flush=True)
        print_command_finish(timing, stream=sys.stderr)
        print("=" * 72, file=sys.stderr, flush=True)
        return int(exc.code) if isinstance(exc.code, int) else 1

    modulus = args.M
    operator_id, operator_id_source = resolve_operator_identity(args.operator_id)
    author_id, author_id_source = resolve_author_identity(
        args.author_id, fallback_operator_id=operator_id
    )
    run_id = args.run_id or f"ctv0100_{PACKAGE_LABEL.replace('-', '_')}_M{modulus}_{timestamp()}"
    output_root: Path | None = None
    output_preflight: dict[str, object] | None = None
    if args.output_dir:
        output_root = _absolute_cli_path(args.output_dir, relative_base=Path.cwd())
        try:
            output_preflight = _preflight_output_root(output_root)
        except BaseException as exc:
            print(f"FAIL: output directory preflight failed: {exc}", file=sys.stderr)
            timing = build_command_timing(command_started_at, command_start_monotonic)
            print("=" * 72, file=sys.stderr, flush=True)
            print("COMMAND FINISHED: FAIL", file=sys.stderr, flush=True)
            print_command_finish(timing, stream=sys.stderr)
            print("=" * 72, file=sys.stderr, flush=True)
            return 2
        workspace = output_root / "runs" / run_id
        results_dir = output_root / "results"
        output_mode = "persistent-output-root"
    else:
        workspace = (
            _absolute_cli_path(args.workspace, relative_base=ROOT)
            if args.workspace
            else ROOT / "runs" / run_id
        )
        results_dir = (
            _absolute_cli_path(args.results_dir, relative_base=ROOT)
            if args.results_dir
            else ROOT / "results"
        )
        output_mode = "legacy-default-or-explicit-paths"

    certificate_dir = workspace / f"finite_check_certificate_M{modulus}"
    logs_dir = workspace / "logs"
    pass_archive = results_dir / f"{run_id}_PASS.zip"
    fail_archive = results_dir / f"{run_id}_FAILED.zip"

    if workspace.exists():
        print(f"FAIL: workspace already exists: {workspace}", file=sys.stderr)
        timing = build_command_timing(command_started_at, command_start_monotonic)
        print("=" * 72, file=sys.stderr, flush=True)
        print("COMMAND FINISHED: FAIL", file=sys.stderr, flush=True)
        print_command_finish(timing, stream=sys.stderr)
        print("=" * 72, file=sys.stderr, flush=True)
        return 2
    workspace.mkdir(parents=True)
    logs_dir.mkdir(parents=True)
    results_dir.mkdir(parents=True, exist_ok=True)

    original_stdout = sys.stdout
    original_stderr = sys.stderr
    internal_log_path = workspace / "execution_console.log"
    logger = InternalConsoleLogger(
        internal_log_path,
        original_stdout=original_stdout,
        original_stderr=original_stderr,
        flush_seconds=args.internal_log_flush_seconds,
        fsync_seconds=args.internal_log_fsync_seconds,
    )
    sys.stdout = logger.stdout
    sys.stderr = logger.stderr

    print_command_start(command_started_at)
    print(f"output_mode                   : {output_mode}", flush=True)
    print(f"output_root                   : {output_root if output_root else '(package-local/default)'}", flush=True)
    print(f"workspace                     : {workspace}", flush=True)
    print(f"results_directory             : {results_dir}", flush=True)
    print(f"author_id                     : {author_id}", flush=True)
    print(f"author_id_source              : {author_id_source}", flush=True)
    print(f"operator_id                   : {operator_id}", flush=True)
    print(f"operator_id_source            : {operator_id_source}", flush=True)
    print(f"mandatory_internal_console_log : {internal_log_path}", flush=True)
    print(
        "internal_log_durability     : "
        f"flush={args.internal_log_flush_seconds:g}s "
        f"fsync={args.internal_log_fsync_seconds:g}s",
        flush=True,
    )

    summary: dict = {
        "public_name": PUBLIC_NAME,
        "public_abbreviation": PUBLIC_ABBREVIATION,
        "public_ui_version": PUBLIC_UI_VERSION,
        "public_ui_status": PUBLIC_UI_STATUS,
        "public_entry_point": PUBLIC_ENTRY_POINT,
        "internal_engine": PACKAGE_LABEL,
        "package_label": PACKAGE_LABEL,
        "interface": "one-command",
        "M": modulus,
        "run_id": run_id,
        "author_id": author_id,
        "author_id_source": author_id_source,
        "operator_id": operator_id,
        "operator_id_source": operator_id_source,
        "workspace": str(workspace),
        "results_directory": str(results_dir),
        "output": {
            "mode": output_mode,
            "output_root": str(output_root) if output_root else "",
            "workspace": str(workspace),
            "results_directory": str(results_dir),
            "preflight": output_preflight or {"status": "NOT_REQUESTED"},
            "google_colab_drive_compatible": True,
        },
        "started_at": command_started_at,
        "command_started_at": command_started_at,
        "status": "RUNNING",
        "io": {
            "child_stdout_reader_thread": True,
            "console_file_writer_thread": True,
            "stage_file_log_flush_seconds": float(args.log_flush_seconds),
            "mandatory_internal_console_log": True,
            "internal_console_log_path": str(internal_log_path),
            "internal_console_log_flush_seconds": float(args.internal_log_flush_seconds),
            "internal_console_log_fsync_seconds": float(args.internal_log_fsync_seconds),
            "external_tee_required": False,
            "file_buffer_bytes": 1024 * 1024,
            "manager_entry_point_check": "single-manager-help-process",
        },
        "stages": {},
    }

    environment_context = {
        "public_name": PUBLIC_NAME,
        "public_ui_version": PUBLIC_UI_VERSION,
        "public_ui_status": PUBLIC_UI_STATUS,
        "public_entry_point": PUBLIC_ENTRY_POINT,
        "internal_engine": PACKAGE_LABEL,
        "package_label": PACKAGE_LABEL,
        "M": modulus,
        "run_id": run_id,
        "author_id": author_id,
        "author_id_source": author_id_source,
        "operator_id": operator_id,
        "operator_id_source": operator_id_source,
        "output_mode": output_mode,
        "output_root": str(output_root) if output_root else "",
    }

    try:
        environment_start = collect_environment_snapshot(
            package_directory=ROOT,
            workspace_directory=workspace,
            phase="program_start",
            context=environment_context,
        )
        environment_start_path = logs_dir / "00_environment_start.json"
        environment_start_text_path = logs_dir / "00_environment_start.txt"
        write_environment_snapshot(environment_start_path, environment_start)
        write_environment_snapshot_text(environment_start_text_path, environment_start)
        summary["environment_start"] = environment_start
        summary["environment_start_file"] = str(environment_start_path)
        summary["environment_start_text_file"] = str(environment_start_text_path)
        write_summary(workspace, summary)
        logger.durability_boundary()

        print_environment_snapshot(environment_start)
        print("=" * 72)
        print(f"{PUBLIC_NAME} (CTV {PUBLIC_UI_VERSION})")
        print(f"Public UI status: {PUBLIC_UI_STATUS}")
        print(f"Internal validation engine: {PACKAGE_LABEL}")
        print(f"ONE-COMMAND EXECUTION: M={modulus}")
        print(f"Workspace: {workspace}")
        print(f"Heartbeat interval: {args.heartbeat_seconds} seconds")
        print(
            "Stage-specific asynchronous log writer: enabled "
            f"(file flush every {args.log_flush_seconds:g} seconds)"
        )
        print("Whole-command internal console log: mandatory and enabled")
        print("External shell tee: optional redundant evidence only")
        print("=" * 72)

        print("\n" + "-" * 72)
        print("STAGE 1/4: environment and source-integrity check")
        print("-" * 72)
        started = time.monotonic()
        environment = check_environment(environment_start)
        elapsed = time.monotonic() - started
        for key, value in environment.items():
            if key == "environment_snapshot":
                continue
            print(f"{key}: {value}")
        write_json(logs_dir / "01_check.json", environment)
        summary["environment"] = environment
        summary["stages"]["check"] = {
            "status": "PASS",
            "exit_code": 0,
            "elapsed_seconds": round(elapsed, 3),
            "log": str(logs_dir / "01_check.json"),
        }
        write_summary(workspace, summary)
        logger.durability_boundary()

        print("\n" + "-" * 72)
        print("STAGE 2/4: M-specific finite-check certificate generation")
        print("-" * 72)
        generate_command = [
            sys.executable,
            "-u",
            str(MANAGER),
            "appendix-i-core-certificate",
            "--M",
            str(modulus),
            "--author-id",
            author_id,
            "--operator-id",
            operator_id,
        ]
        if modulus >= 8192:
            generate_command.append("--allow-auxiliary-M")
        generate_command.extend(
            [
                "--block-size",
                str(args.block_size),
                "--out-dir",
                str(certificate_dir),
                "--fresh",
            ]
        )
        rc, elapsed, io_stats = run_logged(
            generate_command,
            logs_dir / "02_generate.log",
            stage="generate",
            heartbeat_seconds=args.heartbeat_seconds,
            log_flush_seconds=args.log_flush_seconds,
        )
        summary["stages"]["generate"] = {
            "status": STATUS_PASS if rc == 0 else STATUS_FAIL,
            "exit_code": rc,
            "elapsed_seconds": round(elapsed, 3),
            "log": str(logs_dir / "02_generate.log"),
            "io": io_stats,
        }
        write_summary(workspace, summary)
        logger.durability_boundary()
        if rc != 0:
            raise RuntimeError(f"generation failed with exit code {rc}")
        certificate = validate_generation(certificate_dir, modulus)

        print("\n" + "-" * 72)
        print("STAGE 3/4: M-specific finite-check certificate independent verification")
        print("-" * 72)
        verify_command = [
            sys.executable,
            "-u",
            str(MANAGER),
            "verify-appendix-i-core-certificate",
            "--run-dir",
            str(certificate_dir),
            "--M",
            str(modulus),
            "--author-id",
            author_id,
            "--operator-id",
            operator_id,
        ]
        rc, elapsed, io_stats = run_logged(
            verify_command,
            logs_dir / "03_verify.log",
            stage="verify",
            heartbeat_seconds=args.heartbeat_seconds,
            log_flush_seconds=args.log_flush_seconds,
        )
        summary["stages"]["verify"] = {
            "status": STATUS_PASS if rc == 0 else STATUS_FAIL,
            "exit_code": rc,
            "elapsed_seconds": round(elapsed, 3),
            "log": str(logs_dir / "03_verify.log"),
            "io": io_stats,
        }
        write_summary(workspace, summary)
        logger.durability_boundary()
        if rc != 0:
            raise RuntimeError(f"independent verification failed with exit code {rc}")
        verification = validate_verification(certificate_dir, modulus)

        summary["finite_check_certificate"] = {
            "status": certificate.get("status"),
            "certificate_id": certificate.get("core_certificate_id"),
            "certificate_file": str(certificate_dir / f"{_core_certificate_stem(modulus)}.txt"),
            "global_minimum_value_bound": certificate.get("global_minimum_value_bound"),
            "odd_minimum_candidates_audited": certificate.get("odd_minimum_candidates_audited"),
            "nontrivial_positive_integer_periodic_lifts_found": certificate.get(
                "nontrivial_positive_integer_periodic_lifts_found"
            ),
            "trivial_1_loop_confirmed": certificate.get("trivial_1_loop_confirmed"),
            "structural_lambda_x": certificate.get("valid_periodic_lift_structural_lambda_x"),
            "verification_status": verification.get("verification_status"),
        }
        environment_end = collect_environment_snapshot(
            package_directory=ROOT,
            workspace_directory=workspace,
            phase="program_end_before_packaging",
            context=environment_context,
        )
        environment_end_path = logs_dir / "04_environment_end.json"
        write_environment_snapshot(environment_end_path, environment_end)
        summary["environment_end"] = environment_end
        summary["environment_end_file"] = str(environment_end_path)

        summary["status"] = STATUS_PASS
        summary["stages"]["package"] = {
            "status": "RUNNING",
            "exit_code": 0,
            "archive": str(pass_archive),
        }
        write_summary(workspace, summary)
        logger.durability_boundary()

        print("\n" + "-" * 72)
        print("STAGE 4/4: result packaging")
        print("-" * 72)
        package_started = time.monotonic()
        pass_archive.parent.mkdir(parents=True, exist_ok=True)
        with zipfile.ZipFile(
            pass_archive,
            mode="w",
            compression=zipfile.ZIP_DEFLATED,
            compresslevel=9,
            allowZip64=True,
        ) as output:
            _write_workspace_zip_static_entries(output, workspace, run_id)
            package_static_elapsed = time.monotonic() - package_started
            summary["stages"]["package"].update(
                {
                    "status": "PASS",
                    "elapsed_seconds": round(package_static_elapsed, 3),
                    "dynamic_evidence_finalized_after_static_entries": True,
                }
            )
            timing = build_command_timing(command_started_at, command_start_monotonic)
            save_command_timing(summary, workspace, timing)

            print("\n" + "=" * 72)
            print("PASS: all four stages completed")
            print(f"Result ZIP: {pass_archive}")
            print(f"Internal execution log: {internal_log_path}")
            print("Internal log SHA-256 and final ZIP SHA-256 are generated automatically.")
            print("External shell tee is optional and is not required for evidence completeness.")
            print("-" * 72)
            print_command_finish(timing)
            print("=" * 72)
            logger.durability_boundary()

            metadata = _finalize_internal_console_log(
                logger,
                original_stdout=original_stdout,
                original_stderr=original_stderr,
                workspace=workspace,
                logs_dir=logs_dir,
                summary=summary,
            )
            _write_workspace_zip_dynamic_entries(output, workspace, run_id)

        archive_hash = sha256_file(pass_archive)
        hash_path = Path(str(pass_archive) + ".sha256")
        hash_path.write_text(
            f"{archive_hash}  {pass_archive.name}\n",
            encoding="ascii",
            newline="\n",
        )
        summary["result_archive"] = str(pass_archive)
        summary["result_archive_sha256"] = archive_hash
        summary["result_archive_sha256_file"] = str(hash_path)
        summary["internal_console_log"] = metadata
        write_summary(workspace, summary)

        print(f"Final result ZIP: {pass_archive}", file=original_stdout, flush=True)
        print(f"Final SHA-256 file: {hash_path}", file=original_stdout, flush=True)
        print(f"Final SHA-256: {archive_hash}", file=original_stdout, flush=True)
        print(
            f"Internal log status: {metadata.get('status')}",
            file=original_stdout,
            flush=True,
        )
        return 0

    except BaseException as exc:
        if isinstance(exc, KeyboardInterrupt):
            error = "execution interrupted by user"
            exit_code = 130
        else:
            error = str(exc)
            exit_code = 1
        summary["status"] = STATUS_FAIL
        summary["finished_at"] = iso_now()
        summary["error"] = error
        try:
            environment_end = collect_environment_snapshot(
                package_directory=ROOT,
                workspace_directory=workspace,
                phase="program_failure",
                context=environment_context,
            )
            environment_end_path = logs_dir / "04_environment_end.json"
            write_environment_snapshot(environment_end_path, environment_end)
            summary["environment_end"] = environment_end
            summary["environment_end_file"] = str(environment_end_path)
        except Exception as environment_error:
            summary["environment_end_collection_error"] = str(environment_error)
        summary["stages"].setdefault(
            "package",
            {"status": "DIAGNOSTIC", "exit_code": 0, "archive": str(fail_archive)},
        )
        timing = build_command_timing(command_started_at, command_start_monotonic)
        try:
            save_command_timing(summary, workspace, timing)
        except Exception as timing_error:
            print(
                f"WARNING: final command timing record failed: {timing_error}",
                file=sys.stderr,
            )
        print(f"FAIL: {error}", file=sys.stderr)
        print("=" * 72, file=sys.stderr, flush=True)
        print("COMMAND FINISHED: FAIL", file=sys.stderr, flush=True)
        print_command_finish(timing, stream=sys.stderr)
        print(f"Diagnostic ZIP: {fail_archive}", file=sys.stderr, flush=True)
        print("=" * 72, file=sys.stderr, flush=True)
        logger.durability_boundary()

        metadata = _finalize_internal_console_log(
            logger,
            original_stdout=original_stdout,
            original_stderr=original_stderr,
            workspace=workspace,
            logs_dir=logs_dir,
            summary=summary,
        )
        try:
            fail_archive.parent.mkdir(parents=True, exist_ok=True)
            with zipfile.ZipFile(
                fail_archive,
                mode="w",
                compression=zipfile.ZIP_DEFLATED,
                compresslevel=9,
                allowZip64=True,
            ) as output:
                _write_workspace_zip_static_entries(output, workspace, run_id)
                _write_workspace_zip_dynamic_entries(output, workspace, run_id)
            archive_hash = sha256_file(fail_archive)
            hash_path = Path(str(fail_archive) + ".sha256")
            hash_path.write_text(
                f"{archive_hash}  {fail_archive.name}\n",
                encoding="ascii",
                newline="\n",
            )
            summary["diagnostic_archive"] = str(fail_archive)
            summary["diagnostic_archive_sha256"] = archive_hash
            summary["diagnostic_archive_sha256_file"] = str(hash_path)
            summary["internal_console_log"] = metadata
            write_summary(workspace, summary)
            print(f"Diagnostic ZIP: {fail_archive}", file=original_stderr, flush=True)
            print(f"Diagnostic SHA-256 file: {hash_path}", file=original_stderr, flush=True)
        except Exception as package_error:
            print(
                f"WARNING: diagnostic ZIP creation failed: {package_error}",
                file=original_stderr,
                flush=True,
            )
        return exit_code


if __name__ == "__main__":
    raise SystemExit(main())

I.12.2 ctv_environment_snapshot.py

#!/usr/bin/env python3
"""Privacy-safe execution-environment snapshot support for CTV.

Source metadata:
    File name: ctv_environment_snapshot.py
    Program version: X04a
    Source file version: 1.0.2
    Created: 2026-07-29 23:55:10 JST
    Last updated: 2026-08-02 16:32:00 JST

Function summary:
    Collects best-effort operating-system, Python, dependency, CPU, memory, cgroup, and disk
    information without making unavailable platform-specific fields fatal.

Remarks:
    The module uses only the Python standard library. Missing or unsupported environment fields
    are recorded as null and do not alter mathematical verification results.
    Individual source-file versioning starts with this metadata revision. Earlier file-level
    changes are retained in package history but are not reconstructed as separate source-file
    versions.

Change history:
    - 1.0.2 / X04a / 2026-08-02 16:32:00 JST
      Updated X04a Program-membership metadata; executable logic is unchanged.
    - 1.0.1 / X03f / 2026-08-01 23:28:33 JST
      Updated the source metadata header for inclusion in the X03f Program package; executable logic is unchanged.
    - 1.0.0 / X03e / 2026-08-01 05:17:15 JST
      Added the standardized English source metadata header and established the
      initial individual source-file version baseline.

Detailed description:
    This module uses only Python's standard library. Platform-specific fields are
    collected opportunistically; unavailable fields are recorded as null and do
    not stop the mathematical verification workflow.
"""
from __future__ import annotations

import ctypes
import importlib.metadata
import importlib.util
import locale
import os
import platform
import struct
import sys
import time
from datetime import datetime
from pathlib import Path
from typing import Any, Callable

from LIC_status import STATUS_PASS, STATUS_WARN

SCHEMA_ID = "CTV-ENVIRONMENT-SNAPSHOT-v2"


def _iso_now() -> str:
    return datetime.now().astimezone().isoformat(timespec="seconds")


def _safe(label: str, fn: Callable[[], Any], errors: list[str]) -> Any:
    try:
        return fn()
    except Exception as exc:  # best-effort collector; never fail the proof run
        errors.append(f"{label}: {type(exc).__name__}: {exc}")
        return None


def _read_text(path: Path) -> str | None:
    try:
        return path.read_text(encoding="utf-8", errors="replace").strip()
    except OSError:
        return None


def _parse_meminfo() -> dict[str, int]:
    values: dict[str, int] = {}
    text = _read_text(Path("/proc/meminfo"))
    if not text:
        return values
    for line in text.splitlines():
        if ":" not in line:
            continue
        key, rest = line.split(":", 1)
        fields = rest.strip().split()
        if not fields:
            continue
        try:
            number = int(fields[0])
        except ValueError:
            continue
        multiplier = 1024 if len(fields) > 1 and fields[1].lower() == "kb" else 1
        values[key] = number * multiplier
    return values


def _linux_cpu_model() -> str | None:
    text = _read_text(Path("/proc/cpuinfo"))
    if not text:
        return None
    first: dict[str, str] = {}
    for line in text.splitlines():
        if not line.strip() and first:
            break
        if ":" not in line:
            continue
        key, value = line.split(":", 1)
        first[key.strip().lower()] = value.strip()
    for key in ("model name", "hardware"):
        value = first.get(key)
        if value and value.lower() not in {"unknown", "n/a", "none"}:
            return value
    vendor = first.get("vendor_id") or first.get("cpu implementer")
    family = first.get("cpu family")
    model = first.get("model")
    if vendor or family or model:
        return ", ".join(
            part for part in (
                f"vendor={vendor}" if vendor else "",
                f"family={family}" if family else "",
                f"model={model}" if model else "",
            ) if part
        )
    value = first.get("processor")
    return value if value and not value.isdigit() else None


def _linux_process_memory() -> dict[str, int | None]:
    result: dict[str, int | None] = {
        "rss_bytes": None,
        "peak_rss_bytes": None,
    }
    text = _read_text(Path("/proc/self/status"))
    if not text:
        return result
    for line in text.splitlines():
        if ":" not in line:
            continue
        key, rest = line.split(":", 1)
        fields = rest.strip().split()
        if not fields:
            continue
        try:
            value = int(fields[0]) * (1024 if len(fields) > 1 and fields[1].lower() == "kb" else 1)
        except ValueError:
            continue
        if key == "VmRSS":
            result["rss_bytes"] = value
        elif key == "VmHWM":
            result["peak_rss_bytes"] = value
    return result


def _windows_memory() -> dict[str, int | None]:
    result: dict[str, int | None] = {
        "physical_total_bytes": None,
        "physical_available_bytes": None,
        "process_rss_bytes": None,
        "process_peak_rss_bytes": None,
    }
    if os.name != "nt":
        return result

    class MEMORYSTATUSEX(ctypes.Structure):
        _fields_ = [
            ("dwLength", ctypes.c_ulong),
            ("dwMemoryLoad", ctypes.c_ulong),
            ("ullTotalPhys", ctypes.c_ulonglong),
            ("ullAvailPhys", ctypes.c_ulonglong),
            ("ullTotalPageFile", ctypes.c_ulonglong),
            ("ullAvailPageFile", ctypes.c_ulonglong),
            ("ullTotalVirtual", ctypes.c_ulonglong),
            ("ullAvailVirtual", ctypes.c_ulonglong),
            ("ullAvailExtendedVirtual", ctypes.c_ulonglong),
        ]

    status = MEMORYSTATUSEX()
    status.dwLength = ctypes.sizeof(MEMORYSTATUSEX)
    if ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(status)):
        result["physical_total_bytes"] = int(status.ullTotalPhys)
        result["physical_available_bytes"] = int(status.ullAvailPhys)

    class PROCESS_MEMORY_COUNTERS_EX(ctypes.Structure):
        _fields_ = [
            ("cb", ctypes.c_ulong),
            ("PageFaultCount", ctypes.c_ulong),
            ("PeakWorkingSetSize", ctypes.c_size_t),
            ("WorkingSetSize", ctypes.c_size_t),
            ("QuotaPeakPagedPoolUsage", ctypes.c_size_t),
            ("QuotaPagedPoolUsage", ctypes.c_size_t),
            ("QuotaPeakNonPagedPoolUsage", ctypes.c_size_t),
            ("QuotaNonPagedPoolUsage", ctypes.c_size_t),
            ("PagefileUsage", ctypes.c_size_t),
            ("PeakPagefileUsage", ctypes.c_size_t),
            ("PrivateUsage", ctypes.c_size_t),
        ]

    counters = PROCESS_MEMORY_COUNTERS_EX()
    counters.cb = ctypes.sizeof(PROCESS_MEMORY_COUNTERS_EX)
    handle = ctypes.windll.kernel32.GetCurrentProcess()
    if ctypes.windll.psapi.GetProcessMemoryInfo(handle, ctypes.byref(counters), counters.cb):
        result["process_rss_bytes"] = int(counters.WorkingSetSize)
        result["process_peak_rss_bytes"] = int(counters.PeakWorkingSetSize)
    return result


def _cgroup_cpu() -> dict[str, Any]:
    result: dict[str, Any] = {
        "version": None,
        "quota_us": None,
        "period_us": None,
        "quota_cpu_count": None,
    }
    v2 = _read_text(Path("/sys/fs/cgroup/cpu.max"))
    if v2:
        parts = v2.split()
        if len(parts) >= 2:
            result["version"] = 2
            if parts[0] != "max":
                quota = int(parts[0])
                period = int(parts[1])
                result["quota_us"] = quota
                result["period_us"] = period
                result["quota_cpu_count"] = quota / period if period > 0 else None
        return result

    quota_text = _read_text(Path("/sys/fs/cgroup/cpu/cpu.cfs_quota_us"))
    period_text = _read_text(Path("/sys/fs/cgroup/cpu/cpu.cfs_period_us"))
    if quota_text and period_text:
        result["version"] = 1
        quota = int(quota_text)
        period = int(period_text)
        if quota >= 0:
            result["quota_us"] = quota
            result["period_us"] = period
            result["quota_cpu_count"] = quota / period if period > 0 else None
    return result


def _parse_cgroup_integer(path: Path) -> int | None:
    text = _read_text(path)
    if text is None or text == "max":
        return None
    try:
        value = int(text)
    except ValueError:
        return None
    # Kernel may expose an enormous sentinel instead of "max".
    if value >= (1 << 60):
        return None
    return value


def _cgroup_memory() -> dict[str, Any]:
    if Path("/sys/fs/cgroup/memory.max").exists():
        return {
            "version": 2,
            "limit_bytes": _parse_cgroup_integer(Path("/sys/fs/cgroup/memory.max")),
            "current_bytes": _parse_cgroup_integer(Path("/sys/fs/cgroup/memory.current")),
        }
    if Path("/sys/fs/cgroup/memory/memory.limit_in_bytes").exists():
        return {
            "version": 1,
            "limit_bytes": _parse_cgroup_integer(Path("/sys/fs/cgroup/memory/memory.limit_in_bytes")),
            "current_bytes": _parse_cgroup_integer(Path("/sys/fs/cgroup/memory/memory.usage_in_bytes")),
        }
    return {"version": None, "limit_bytes": None, "current_bytes": None}


def _environment_kind() -> dict[str, Any]:
    msystem = os.environ.get("MSYSTEM")
    colab_module = False
    try:
        colab_module = importlib.util.find_spec("google.colab") is not None
    except (ImportError, AttributeError, ValueError):
        colab_module = False
    is_colab = bool(
        os.environ.get("COLAB_RELEASE_TAG")
        or os.environ.get("COLAB_GPU")
        or os.environ.get("COLAB_TPU_ADDR")
        or colab_module
    )
    cgroup_text = _read_text(Path("/proc/1/cgroup")) or ""
    is_container = Path("/.dockerenv").exists() or any(
        token in cgroup_text.lower() for token in ("docker", "containerd", "kubepods", "podman")
    )
    is_wsl = "microsoft" in (platform.release() or "").lower()
    if is_colab:
        kind = "google-colab"
    elif msystem:
        kind = "msys2"
    elif os.name == "nt":
        kind = "windows"
    elif is_wsl:
        kind = "wsl"
    elif is_container:
        kind = "linux-container"
    else:
        kind = platform.system().lower() or "unknown"
    return {
        "kind": kind,
        "is_google_colab": is_colab,
        "is_msys2": bool(msystem),
        "is_container": is_container,
        "is_wsl": is_wsl,
        "whitelisted_environment": {
            key: os.environ.get(key)
            for key in ("MSYSTEM", "MSYSTEM_CARCH", "PROCESSOR_ARCHITECTURE", "COLAB_RELEASE_TAG", "CI")
            if os.environ.get(key) is not None
        },
    }


def _dependency_versions() -> dict[str, str | None]:
    result: dict[str, str | None] = {}
    for package in ("numpy", "scipy"):
        try:
            result[package] = importlib.metadata.version(package)
        except importlib.metadata.PackageNotFoundError:
            result[package] = None
    return result


def _disk(path: Path) -> dict[str, Any]:
    import shutil

    usage = shutil.disk_usage(path)
    return {
        "path": str(path),
        "total_bytes": usage.total,
        "used_bytes": usage.used,
        "free_bytes": usage.free,
    }


def collect_environment_snapshot(
    *,
    package_directory: Path,
    workspace_directory: Path,
    phase: str,
    context: dict[str, Any] | None = None,
) -> dict[str, Any]:
    """Collect a privacy-safe best-effort snapshot without external packages."""
    errors: list[str] = []
    package_directory = package_directory.resolve()
    workspace_directory = workspace_directory.resolve()
    meminfo = _safe("linux meminfo", _parse_meminfo, errors) or {}
    winmem = _safe("windows memory", _windows_memory, errors) or {}
    process_memory = _safe("linux process memory", _linux_process_memory, errors) or {}
    cgroup_cpu = _safe("cgroup cpu", _cgroup_cpu, errors) or {}
    cgroup_memory = _safe("cgroup memory", _cgroup_memory, errors) or {}

    logical = _safe("os.cpu_count", os.cpu_count, errors)
    affinity = _safe(
        "cpu affinity",
        lambda: len(os.sched_getaffinity(0)) if hasattr(os, "sched_getaffinity") else None,
        errors,
    )
    quota_count = cgroup_cpu.get("quota_cpu_count")
    effective_candidates = [
        float(value)
        for value in (logical, affinity, quota_count)
        if isinstance(value, (int, float)) and value > 0
    ]
    effective_cpu_limit = min(effective_candidates) if effective_candidates else None

    physical_total = meminfo.get("MemTotal") or winmem.get("physical_total_bytes")
    physical_available = meminfo.get("MemAvailable") or winmem.get("physical_available_bytes")
    cgroup_limit = cgroup_memory.get("limit_bytes")
    memory_candidates = [
        int(value)
        for value in (physical_total, cgroup_limit)
        if isinstance(value, int) and value > 0
    ]
    effective_memory_limit = min(memory_candidates) if memory_candidates else None

    cpu_model = (
        _safe("linux cpu model", _linux_cpu_model, errors)
        or os.environ.get("PROCESSOR_IDENTIFIER")
        or _safe("platform.processor", platform.processor, errors)
        or None
    )
    libc_name, libc_version = _safe("libc version", platform.libc_ver, errors) or ("", "")
    locale_value = _safe("locale", lambda: locale.setlocale(locale.LC_ALL, None), errors)
    timezone_name = _safe(
        "timezone",
        lambda: time.tzname[1 if time.daylight else 0],
        errors,
    )
    utc_offset = _safe(
        "utc offset",
        lambda: datetime.now().astimezone().strftime("%z"),
        errors,
    )

    snapshot: dict[str, Any] = {
        "schema_id": SCHEMA_ID,
        "captured_at": _iso_now(),
        "phase": phase,
        "status": STATUS_PASS if not errors else STATUS_WARN,
        "warning_count": len(errors),
        "context": context or {},
        "execution_environment": _environment_kind(),
        "operating_system": {
            "system": platform.system(),
            "release": platform.release(),
            "version": platform.version(),
            "machine": platform.machine(),
            "platform": platform.platform(),
            "sys_platform": sys.platform,
            "os_name": os.name,
            "libc_name": libc_name or None,
            "libc_version": libc_version or None,
        },
        "python": {
            "version": sys.version,
            "version_info": list(sys.version_info[:5]),
            "implementation": platform.python_implementation(),
            "executable": sys.executable,
            "bitness": struct.calcsize("P") * 8,
            "compiler": platform.python_compiler(),
            "build": list(platform.python_build()),
            "default_encoding": sys.getdefaultencoding(),
            "filesystem_encoding": sys.getfilesystemencoding(),
        },
        "cpu": {
            "logical_cpus_visible": logical,
            "cpu_affinity_count": affinity,
            "cgroup": cgroup_cpu,
            "effective_cpu_limit": effective_cpu_limit,
            "model": cpu_model,
        },
        "memory": {
            "physical_total_bytes": physical_total,
            "physical_available_bytes": physical_available,
            "cgroup": cgroup_memory,
            "effective_limit_bytes": effective_memory_limit,
            "process_rss_bytes": process_memory.get("rss_bytes") or winmem.get("process_rss_bytes"),
            "process_peak_rss_bytes": process_memory.get("peak_rss_bytes") or winmem.get("process_peak_rss_bytes"),
        },
        "disk": {
            "package": _safe("package disk", lambda: _disk(package_directory), errors),
            "workspace": _safe("workspace disk", lambda: _disk(workspace_directory), errors),
        },
        "dependencies": _dependency_versions(),
        "locale_and_time": {
            "locale": locale_value,
            "preferred_encoding": _safe("preferred encoding", locale.getpreferredencoding, errors),
            "timezone_name": timezone_name,
            "utc_offset": utc_offset,
        },
        "process": {
            "pid": os.getpid(),
            "current_working_directory": str(Path.cwd()),
            "package_directory": str(package_directory),
            "workspace_directory": str(workspace_directory),
        },
        "privacy_policy": {
            "hostname_recorded": False,
            "username_recorded": False,
            "ip_address_recorded": False,
            "full_environment_recorded": False,
            "environment_variable_policy": "whitelist-only",
        },
        "collection_errors": errors,
    }
    return snapshot


def format_snapshot_lines(snapshot: dict[str, Any]) -> list[str]:
    """Return a stable concise console representation."""
    env = snapshot.get("execution_environment", {})
    osinfo = snapshot.get("operating_system", {})
    py = snapshot.get("python", {})
    cpu = snapshot.get("cpu", {})
    memory = snapshot.get("memory", {})
    disk = snapshot.get("disk", {}).get("workspace") or {}
    deps = snapshot.get("dependencies", {})
    return [
        f"environment_snapshot_schema : {snapshot.get('schema_id')}",
        f"environment_snapshot_phase  : {snapshot.get('phase')}",
        f"environment_snapshot_status : {snapshot.get('status')}",
        f"environment_kind            : {env.get('kind')}",
        f"platform                    : {osinfo.get('platform')}",
        f"machine                     : {osinfo.get('machine')}",
        f"python_version              : {py.get('version')}",
        f"python_executable           : {py.get('executable')}",
        f"python_bitness              : {py.get('bitness')}",
        f"logical_cpus_visible        : {cpu.get('logical_cpus_visible')}",
        f"cpu_affinity_count          : {cpu.get('cpu_affinity_count')}",
        f"cgroup_cpu_quota            : {cpu.get('cgroup', {}).get('quota_cpu_count')}",
        f"effective_cpu_limit         : {cpu.get('effective_cpu_limit')}",
        f"cpu_model                   : {cpu.get('model')}",
        f"physical_memory_total_bytes : {memory.get('physical_total_bytes')}",
        f"memory_available_bytes      : {memory.get('physical_available_bytes')}",
        f"cgroup_memory_limit_bytes   : {memory.get('cgroup', {}).get('limit_bytes')}",
        f"effective_memory_limit_bytes: {memory.get('effective_limit_bytes')}",
        f"process_rss_bytes           : {memory.get('process_rss_bytes')}",
        f"workspace_disk_free_bytes   : {disk.get('free_bytes')}",
        f"numpy_version               : {deps.get('numpy')}",
        f"scipy_version               : {deps.get('scipy')}",
        f"collection_error_count      : {len(snapshot.get('collection_errors', []))}",
    ]

I.12.3 ctv_internal_console_log.py

#!/usr/bin/env python3
"""Durable whole-command console logging for the CTV driver.

Source metadata:
    File name: ctv_internal_console_log.py
    Program version: X04a
    Source file version: 1.0.2
    Created: 2026-07-25 12:00:02 JST
    Last updated: 2026-08-02 16:32:00 JST

Function summary:
    Mirrors stdout and stderr to a workspace log with line-boundary flushing, periodic flush and
    fsync, integrity metadata, and explicit durability boundaries.

Remarks:
    Console output remains available when the internal file sink fails. Stage-specific child-
    process logging is handled separately by the driver.
    Individual source-file versioning starts with this metadata revision. Earlier file-level
    changes are retained in package history but are not reconstructed as separate source-file
    versions.

Change history:
    - 1.0.2 / X04a / 2026-08-02 16:32:00 JST
      Updated X04a Program-membership metadata; executable logic is unchanged.
    - 1.0.1 / X03f / 2026-08-01 23:28:33 JST
      Updated the source metadata header for inclusion in the X03f Program package; executable logic is unchanged.
    - 1.0.0 / X03e / 2026-08-01 05:17:15 JST
      Added the standardized English source metadata header and established the
      initial individual source-file version baseline.

Detailed description:
    The logger mirrors stdout and stderr to an internal log file inside the run
    workspace.  Console output remains available even when the internal file sink
    fails.  File flushes occur at line boundaries or after a short interval, and
    OS-level fsync is performed periodically and at explicit durability boundaries.
"""
from __future__ import annotations

import hashlib
import os
import sys
import threading
import time
from datetime import datetime
from pathlib import Path
from typing import TextIO


def _iso_now() -> str:
    return datetime.now().astimezone().isoformat(timespec="seconds")


def _sha256_file(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as stream:
        for block in iter(lambda: stream.read(1024 * 1024), b""):
            digest.update(block)
    return digest.hexdigest()


class _TeeTextStream:
    """Text stream proxy writing to the original console and shared log."""

    def __init__(
        self,
        owner: "InternalConsoleLogger",
        original: TextIO,
        stream_name: str,
    ) -> None:
        self._owner = owner
        self._original = original
        self._stream_name = stream_name

    def write(self, text: str) -> int:
        return self._owner.write(self._original, self._stream_name, text)

    def flush(self) -> None:
        self._owner.flush(self._original)

    def isatty(self) -> bool:
        try:
            return bool(self._original.isatty())
        except Exception:
            return False

    def fileno(self) -> int:
        return self._original.fileno()

    @property
    def encoding(self):
        return getattr(self._original, "encoding", "utf-8")

    @property
    def errors(self):
        return getattr(self._original, "errors", "replace")

    def writable(self) -> bool:
        return True

    def __getattr__(self, name: str):
        return getattr(self._original, name)


class InternalConsoleLogger:
    """Whole-command durable internal console logger.

    Log-write failures are recorded but do not terminate the verification
    computation.  The original console streams continue to receive output.
    """

    def __init__(
        self,
        path: Path,
        *,
        original_stdout: TextIO | None = None,
        original_stderr: TextIO | None = None,
        flush_seconds: float = 1.0,
        fsync_seconds: float = 60.0,
    ) -> None:
        self.path = path
        self.original_stdout = original_stdout or sys.stdout
        self.original_stderr = original_stderr or sys.stderr
        self.flush_seconds = max(0.0, float(flush_seconds))
        self.fsync_seconds = max(1.0, float(fsync_seconds))
        self.started_at = _iso_now()
        self.closed_at = ""
        self._lock = threading.RLock()
        self._log = path.open(
            "x",
            encoding="utf-8",
            newline="\n",
            buffering=1,
        )
        self._closed = False
        self._failed = False
        self._error = ""
        self._warning_emitted = False
        self._total_chars = 0
        self._write_calls = 0
        self._flush_count = 0
        self._fsync_count = 0
        self._last_flush = time.monotonic()
        self._last_fsync = self._last_flush
        self.stdout = _TeeTextStream(self, self.original_stdout, "stdout")
        self.stderr = _TeeTextStream(self, self.original_stderr, "stderr")

    def _mark_failure(self, exc: BaseException) -> None:
        if not self._failed:
            self._failed = True
            self._error = f"{type(exc).__name__}: {exc}"
        if not self._warning_emitted:
            self._warning_emitted = True
            try:
                self.original_stderr.write(
                    "\nINTERNAL_LOG_WRITE_FAILURE: " + self._error + "\n"
                )
                self.original_stderr.flush()
            except Exception:
                pass

    def _flush_file(self, *, force_fsync: bool) -> None:
        if self._failed or self._closed:
            return
        try:
            self._log.flush()
            self._flush_count += 1
            self._last_flush = time.monotonic()
            now = self._last_flush
            if force_fsync or now - self._last_fsync >= self.fsync_seconds:
                os.fsync(self._log.fileno())
                self._fsync_count += 1
                self._last_fsync = now
        except BaseException as exc:
            self._mark_failure(exc)

    def write(self, original: TextIO, stream_name: str, text: str) -> int:
        if not text:
            return 0
        with self._lock:
            # Preserve console output even if the internal log is unavailable.
            written = original.write(text)
            self._write_calls += 1
            self._total_chars += len(text)
            if not self._failed and not self._closed:
                try:
                    self._log.write(text)
                    now = time.monotonic()
                    line_boundary = "\n" in text
                    interval_due = now - self._last_flush >= self.flush_seconds
                    if line_boundary or interval_due:
                        self._flush_file(force_fsync=False)
                except BaseException as exc:
                    self._mark_failure(exc)
            return len(text) if written is None else int(written)

    def flush(self, original: TextIO | None = None) -> None:
        with self._lock:
            if original is not None:
                try:
                    original.flush()
                except Exception:
                    pass
            self._flush_file(force_fsync=False)

    def durability_boundary(self) -> None:
        """Flush and fsync the internal log without interrupting computation."""
        with self._lock:
            try:
                self.original_stdout.flush()
            except Exception:
                pass
            try:
                self.original_stderr.flush()
            except Exception:
                pass
            self._flush_file(force_fsync=True)

    def close(self) -> dict[str, object]:
        with self._lock:
            if not self._closed:
                self.durability_boundary()
                try:
                    self._log.close()
                except BaseException as exc:
                    self._mark_failure(exc)
                self._closed = True
                self.closed_at = _iso_now()

        size_bytes = self.path.stat().st_size if self.path.is_file() else 0
        sha256 = _sha256_file(self.path) if self.path.is_file() else ""
        return {
            "schema_id": "CTV-INTERNAL-CONSOLE-LOG-v1",
            "status": "FAILED" if self._failed else "COMPLETE",
            "path": str(self.path),
            "file_name": self.path.name,
            "size_bytes": size_bytes,
            "sha256": sha256,
            "started_at": self.started_at,
            "closed_at": self.closed_at,
            "total_output_chars": self._total_chars,
            "write_calls": self._write_calls,
            "flush_count": self._flush_count,
            "fsync_count": self._fsync_count,
            "flush_seconds": self.flush_seconds,
            "fsync_seconds": self.fsync_seconds,
            "write_failure": self._failed,
            "error": self._error,
            "stdout_and_stderr_combined": True,
            "external_tee_required": False,
        }

I.12.4 LIC_appendix_i_core_certificate.py

#!/usr/bin/env python3
"""Generator for the portable two-layer Appendix-I core certificate.

Source metadata:
    File name: LIC_appendix_i_core_certificate.py
    Program version: X04a
    Source file version: 1.0.2
    Created: 2026-07-29 23:55:10 JST
    Last updated: 2026-08-02 16:32:00 JST

Function summary:
    Builds the self-describing core certificate, binds Layer 1 and Layer 2 child artifacts,
    writes machine-readable and human-readable forms, and emits certificate hash metadata.

Remarks:
    The certificate records evidence identities and digests; it does not replace the
    mathematical finite-reduction argument stated in the paper.
    Individual source-file versioning starts with this metadata revision. Earlier file-level
    changes are retained in package history but are not reconstructed as separate source-file
    versions.

Change history:
    - 1.0.2 / X04a / 2026-08-02 16:32:00 JST
      Updated X04a Program-membership metadata; executable logic is unchanged.
    - 1.0.1 / X03f / 2026-08-01 23:28:33 JST
      Updated the source metadata header for inclusion in the X03f Program package; executable logic is unchanged.
    - 1.0.0 / X03e / 2026-08-01 05:17:15 JST
      Added the standardized English source metadata header and established the
      initial individual source-file version baseline.
"""
from __future__ import annotations

import hashlib
import json
from datetime import datetime
from pathlib import Path
from typing import Dict
from zoneinfo import ZoneInfo

from LIC_certificate_metadata import add_creation_metadata, certificate_digest
from LIC_certificate_logical_paths import EXPECTED_CHILD_PATHS, path_policy_record
from LIC_complete_cycle_classification import write_complete_classification
from LIC_cycle_minimum_bound import logical_graph_sha256
from LIC_r_micrograph import build_r_micrograph
from LIC_complete_cycle_classification_verifier import verify_run as verify_complete_classification
from LIC_structural_lambda_certificate import write_structural_lambda_certificate
from LIC_structural_lambda_certificate_verifier import verify_run as verify_structural_lambda
from LIC_version import PACKAGE_LABEL, PACKAGE_VERSION
from LIC_status import STATUS_FAIL, STATUS_PASS

__program_id__ = "LIC_appendix_i_core_certificate"
__version__ = PACKAGE_VERSION
CORE_ID = "LIC-APPENDIX-I-CORE-CERTIFICATE-v7"
EXPECTED_STRUCTURAL_LAMBDA_X = "1"
FIXED_JUDGMENT_FIXED = "Fixed"
FIXED_JUDGMENT_NOT_FIXED = "NOT_FIXED"
FIXED_JUDGMENT_UNVERIFIED = "UNVERIFIED"
FIXED_JUDGMENT_VALUES = frozenset({
    FIXED_JUDGMENT_FIXED,
    FIXED_JUDGMENT_NOT_FIXED,
    FIXED_JUDGMENT_UNVERIFIED,
})
def certificate_scope(M: int) -> str:
    return (
        f"M={int(M)} derived logical R-graph simple extreme-cycle positive-integer "
        "periodic-lift complete classification, the resulting structural value, "
        "and the Fixed judgment against expected lambda_x^str=1"
    )


def certificate_stem(M: int) -> str:
    return f"appendix_i_core_certificate_M{int(M)}"


def certificate_paths(out_dir: Path, M: int) -> Dict[str, Path]:
    out_dir = Path(out_dir)
    stem = certificate_stem(M)
    return {
        "json": out_dir / f"{stem}.json",
        "txt": out_dir / f"{stem}.txt",
        "report": out_dir / f"{stem}_report.md",
        "verify_summary": out_dir / f"{stem}_verify_summary.json",
        "sha256": out_dir / f"{stem}.sha256",
    }


def write_certificate_hash_manifest(out_dir: Path, M: int) -> Path:
    paths = certificate_paths(out_dir, M)
    entries = []
    for key in ("json", "txt", "report", "verify_summary"):
        path = paths[key]
        if path.is_file():
            entries.append(f"{_sha(path)}  {path.name}")
    paths["sha256"].write_text("\n".join(entries) + "\n", encoding="ascii", newline="\n")
    return paths["sha256"]
_STATUS_PASS = STATUS_PASS
_STATUS_FAIL = STATUS_FAIL


def _canonical(obj: object) -> bytes:
    return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")


def _digest(obj: object) -> str:
    return hashlib.sha256(_canonical(obj)).hexdigest()


def _sha(path: Path) -> str:
    h = hashlib.sha256()
    with Path(path).open("rb") as f:
        for block in iter(lambda: f.read(1 << 20), b""):
            h.update(block)
    return h.hexdigest()


def _child_artifact_records(out_dir: Path) -> Dict[str, Dict[str, str]]:
    """Build the normative logical-path + hash records for all child evidence."""
    records: Dict[str, Dict[str, str]] = {}
    for role, logical_path in EXPECTED_CHILD_PATHS.items():
        artifact_path = out_dir / logical_path
        records[role] = {
            "logical_path": logical_path,
            "size_bytes": artifact_path.stat().st_size,
            "sha256": _sha(artifact_path),
        }
    return records


def _load_json(path: Path) -> Dict[str, object]:
    value = json.loads(Path(path).read_text(encoding="utf-8"))
    if not isinstance(value, dict):
        raise ValueError(f"JSON root is not an object: {path}")
    return value


def _micrograph_record(M: int) -> Dict[str, object]:
    graph = build_r_micrograph(int(M))
    payload = {
        "M": int(M),
        "states": [state.as_dict() for state in graph.states],
        "edges": [edge.as_dict() for edge in graph.edges],
    }
    return {
        "state_count": len(graph.states),
        "microedge_count": len(graph.edges),
        "sha256": _digest(payload),
    }


def _jst(value: object) -> str:
    if not isinstance(value, str) or not value:
        return ""
    return datetime.fromisoformat(value).astimezone(ZoneInfo("Asia/Tokyo")).strftime(
        "%Y-%m-%d %H:%M:%S JST"
    )



def _structural_value_set(structural: Dict[str, object]) -> list[str]:
    """Return the independently reconstructed structural-value set.

    The expected value is intentionally not used here.  This function only
    reflects the Layer 2 evidence generated from the Layer 1 classification.
    """
    exact = structural.get("structural_lambda_x_exact")
    count = structural.get("valid_periodic_lift_extreme_structures")
    if count == 1 and isinstance(exact, str) and exact:
        return [exact]
    return []


def _fixed_judgment_from_conditions(conditions: Dict[str, bool]) -> str:
    prerequisite_names = (
        "candidate_audit_range_complete",
        "all_candidates_decided",
        "layer_1_complete_classification_independent_verify",
        "valid_extreme_structure_set_complete",
        "layer_2_all_structural_values_reconstructed",
    )
    if not all(conditions.get(name) is True for name in prerequisite_names):
        return FIXED_JUDGMENT_UNVERIFIED
    if (
        conditions.get("reconstructed_structural_value_set_is_singleton_expected") is True
        and conditions.get("reconstructed_value_matches_expected") is True
    ):
        return FIXED_JUDGMENT_FIXED
    return FIXED_JUDGMENT_NOT_FIXED

def write_human_readable_certificate(core: Dict[str, object], out_dir: Path) -> None:
    """Write only the human-readable representation of the finite-check certificate.

    This output contains certificate fields and verified results only. It does not
    generate paper section headings, explanatory prose, theorem-condition mapping,
    theorem application, conclusions, or cross-references.
    """
    out_dir = Path(out_dir)
    fields = [
        ("finite-check certificate id", core.get("core_certificate_id")),
        ("package label", core.get("package_label")),
        ("b", core.get("b")),
        ("M", core.get("M")),
        ("N_M", core.get("maximum_simple_logical_cycle_length")),
        ("certificate author id", core.get("certificate_author_id")),
        ("certificate generation operator id", core.get("certificate_generation_operator_id")),
        ("certificate verification operator id", core.get("certificate_verification_operator_id")),
        ("certificate generator program id", core.get("certificate_generator_program_id")),
        ("certificate verifier program id", core.get("certificate_verifier_program_id")),
        ("finite-check certificate created at", _jst(core.get("certificate_created_at"))),
        ("finite-check certificate verified at", _jst(core.get("certificate_verified_at"))),
        ("finite-check certificate verification status", core.get("certificate_verification_status")),
        ("exact R-micrograph state count", core.get("exact_r_micrograph_state_count")),
        ("exact R-micrograph microedge count", core.get("exact_r_micrograph_microedge_count")),
        ("exact R-micrograph hash payload fields", core.get("exact_r_micrograph_hash_payload_fields")),
        ("exact R-micrograph SHA-256", core.get("exact_r_micrograph_sha256")),
        ("exact R-micrograph state-set verify", core.get("exact_r_micrograph_state_set_independent_verify")),
        ("exact R-micrograph microedge-set verify", core.get("exact_r_micrograph_microedge_set_independent_verify")),
        ("exact R-micrograph transition verify", core.get("exact_r_micrograph_transition_structure_independent_verify")),
        ("exact R-micrograph independent verify", core.get("exact_r_micrograph_independent_verify")),
        ("derived logical R-graph odd state count", core.get("derived_logical_r_graph_odd_state_count")),
        ("derived logical R-graph logical edge count", core.get("derived_logical_r_graph_logical_edge_count")),
        ("derived logical R-graph hash payload fields", core.get("derived_logical_r_graph_hash_payload_fields")),
        ("derived logical R-graph SHA-256", core.get("derived_logical_r_graph_sha256")),
        ("derived logical R-graph odd-state-set verify", core.get("derived_logical_r_graph_odd_state_set_independent_verify")),
        ("derived logical R-graph edge-set verify", core.get("derived_logical_r_graph_logical_edge_set_independent_verify")),
        ("logical-edge microedge-sequence verify", core.get("derived_logical_r_graph_microedge_sequence_independent_verify")),
        ("logical-edge division-label verify", core.get("derived_logical_r_graph_division_label_independent_verify")),
        ("derived logical R-graph hash-binding verify", core.get("derived_logical_r_graph_hash_binding_independent_verify")),
        ("derived logical R-graph independent verify", core.get("derived_logical_r_graph_independent_verify")),
        ("finite circulation bridge graph binding verify", core.get("finite_circulation_bridge_graph_binding_independent_verify")),
        ("finite circulation bridge length verify", core.get("finite_circulation_bridge_length_bound_independent_verify")),
        ("finite circulation bridge independent verify", core.get("finite_circulation_bridge_independent_verify")),
        ("minimum-bound length rows", core.get("minimum_bound_length_row_count")),
        ("global minimum-value bound B_M^global", core.get("global_minimum_value_bound")),
        ("global bound attained at L", ", ".join(str(x) for x in core.get("minimum_bound_global_argmax_lengths", []))),
        ("minimum-bound lengths SHA-256", core.get("minimum_bound_lengths_sha256")),
        ("all-length bounds exact/maximal verify", core.get("minimum_bound_rows_exact_and_maximal_independent_verify")),
        ("global minimum-value bound verify", core.get("minimum_bound_global_bound_independent_verify")),
        ("global-bound argmax verify", core.get("minimum_bound_global_argmax_independent_verify")),
        ("minimum-bound independent verify", core.get("minimum_bound_independent_verify")),
        ("odd minimum candidates expected", core.get("expected_odd_minimum_candidates")),
        ("odd minimum candidates audited", core.get("odd_minimum_candidates_audited")),
        ("odd minimum candidate coverage complete", "PASS" if core.get("odd_minimum_candidate_coverage_complete") is True else "FAIL"),
        ("candidate-count independent verify", core.get("odd_minimum_candidate_count_independent_verify")),
        ("candidate-blocks independent verify", core.get("minimum_candidate_blocks_independent_verify")),
        ("minimum-candidate audit independent verify", core.get("minimum_candidate_audit_independent_verify")),
        ("RETURNED_TO_START", core.get("returned_to_start_count")),
        ("nontrivial returned candidates", core.get("nontrivial_returned_candidates")),
        ("DESCENDED_BELOW_START", core.get("descended_below_start_count")),
        ("NO_RETURN_WITHIN_MAX_LENGTH", core.get("no_return_within_max_length_count")),
        ("trivial loop", core.get("trivial_loop")),
        ("terminal-counts independent verify", core.get("terminal_counts_independent_verify")),
        ("returned-cycle details independent verify", core.get("returned_cycle_details_independent_verify")),
        ("nontrivial-return-zero independent verify", core.get("nontrivial_return_zero_independent_verify")),
        ("trivial-loop-only independent verify", core.get("trivial_loop_only_independent_verify")),
        ("Layer 1 independent verify", core.get("layer_1_independent_verify")),
        ("Layer 2 independent verify", core.get("layer_2_independent_verify")),
        ("structural value lambda_x^str", core.get("valid_periodic_lift_structural_lambda_x")),
        ("expected structural value lambda_x^str", core.get("expected_valid_periodic_lift_structural_lambda_x")),
        (
            "structural value lambda_x^str set",
            "{" + ", ".join(str(x) for x in core.get("valid_periodic_lift_structural_lambda_x_values", [])) + "}",
        ),
        ("structural value lambda_x^str fixed judgment", core.get("structural_lambda_x_fixed_judgment")),
        (
            "structural value fixed judgment independent verify",
            core.get("structural_lambda_x_fixed_judgment_independent_verify"),
        ),
        ("core certificate independent verify", core.get("certificate_verification_status")),
        ("core certificate verified at", _jst(core.get("certificate_verified_at"))),
    ]
    label_width = max(len(label) for label, _ in fields)
    body = [f"{label:<{label_width}} : {value}" for label, value in fields]
    paths = certificate_paths(out_dir, int(core.get("M")))
    txt_path = paths["txt"]
    txt_path.write_text("\n".join(body) + "\n", encoding="utf-8", newline="\n")
    write_certificate_hash_manifest(out_dir, int(core.get("M")))

def write_core_certificate(M: int, out_dir: Path, block_size: int = 4096) -> Dict[str, object]:
    """Generate the normative two-layer certificate.

    Layer 1: complete positive-integer periodic-lift classification.
    Layer 2: structural lambda_x=1 derived from Layer 1.

    All child evidence is identified by normalized logical POSIX-relative paths
    rooted at the core-certificate directory. Runtime absolute paths remain a log
    concern and are never stored in the normative certificate or its hash chain.

    Legacy LP numerical consistency data is intentionally not an input and is not
    included in the certificate hash chain or issuance gate.
    """
    out_dir = Path(out_dir)
    out_dir.mkdir(parents=True, exist_ok=True)
    classification_dir = out_dir / "layer1_periodic_lift_classification"
    structural_dir = out_dir / "layer2_structural_lambda"

    classification = write_complete_classification(int(M), classification_dir, block_size=block_size)
    classification_verify = verify_complete_classification(classification_dir)
    structural = write_structural_lambda_certificate(classification_dir, structural_dir)
    structural_verify = verify_structural_lambda(structural_dir, classification_dir)

    bridge = _load_json(
        classification_dir / "finite_lp_cycle_bridge" / "finite_lp_cycle_bridge_certificate.json"
    )
    bridge_verify = _load_json(
        classification_dir / "finite_lp_cycle_bridge" / "finite_lp_cycle_bridge_verify_summary.json"
    )
    minimum_bound = _load_json(
        classification_dir
        / "minimum_candidate_audit"
        / "minimum_bound"
        / "cycle_minimum_bound_certificate.json"
    )
    minimum_bound_verify = _load_json(
        classification_dir
        / "minimum_candidate_audit"
        / "minimum_bound"
        / "cycle_minimum_bound_verify_summary.json"
    )
    minimum_audit = _load_json(
        classification_dir
        / "minimum_candidate_audit"
        / "cycle_minimum_candidate_audit_summary.json"
    )
    minimum_audit_verify = _load_json(
        classification_dir
        / "minimum_candidate_audit"
        / "cycle_minimum_candidate_audit_verify_summary.json"
    )
    micrograph = _micrograph_record(int(M))
    logical_hash, logical_odd_states, logical_edges = logical_graph_sha256(int(M))

    classification_ok = (
        classification_verify.get("verification_status") == "PASS"
        and classification.get("status")
        == STATUS_PASS
        and classification.get("pass_trivial_only") is True
        and int(classification.get("nontrivial_positive_integer_periodic_lifts_found", -1)) == 0
        and classification.get("trivial_1_loop_confirmed") is True
    )
    structural_ok = (
        structural_verify.get("verification_status") == "PASS"
        and structural.get("status") == STATUS_PASS
        and structural.get("structural_lambda_x_exact") == "1"
        and structural.get("underlying_graph_edge_deletion_used") is False
        and structural.get("legacy_catalog_exclusion_used") is False
    )

    minimum_audit_checks = minimum_audit_verify.get("checks", {})
    expected_candidates = (int(minimum_bound.get("global_minimum_value_bound", -1)) + 1) // 2
    audited_candidates = int(minimum_audit.get("total_odd_minimum_candidates", -1))
    returned_count = int(minimum_audit.get("returned_to_start_count", -1))
    descended_count = int(minimum_audit.get("descended_below_start_count", -1))
    undecided_count = int(minimum_audit.get("no_return_within_max_length_count", -1))
    structural_values = _structural_value_set(structural)
    fixed_conditions: Dict[str, bool] = {
        "candidate_audit_range_complete": (
            minimum_audit_verify.get("verification_status") == "PASS"
            and minimum_audit_checks.get("candidate_total_ok") is True
            and minimum_audit_checks.get("blocks_exact_match") is True
            and minimum_audit_checks.get("blocks_hash_ok") is True
            and audited_candidates == expected_candidates
        ),
        "all_candidates_decided": (
            minimum_audit_verify.get("verification_status") == "PASS"
            and minimum_audit_checks.get("terminal_counts_ok") is True
            and undecided_count == 0
            and returned_count + descended_count + undecided_count == audited_candidates
        ),
        "layer_1_complete_classification_independent_verify": (
            classification_verify.get("verification_status") == "PASS"
            and classification.get("status") == STATUS_PASS
        ),
        "valid_extreme_structure_set_complete": (
            classification_verify.get("verification_status") == "PASS"
            and classification.get("pass_trivial_only") is True
            and int(classification.get("positive_integer_periodic_lifts_found", -1)) == 1
            and int(classification.get("nontrivial_positive_integer_periodic_lifts_found", -1)) == 0
            and classification.get("trivial_1_loop_confirmed") is True
        ),
        "layer_2_all_structural_values_reconstructed": (
            structural_verify.get("verification_status") == "PASS"
            and structural.get("status") == STATUS_PASS
            and int(structural.get("valid_periodic_lift_extreme_structures", -1))
            == len(structural_values)
            == 1
        ),
        "reconstructed_structural_value_set_is_singleton_expected": (
            structural_values == [EXPECTED_STRUCTURAL_LAMBDA_X]
        ),
        "reconstructed_value_matches_expected": (
            structural.get("structural_lambda_x_exact") == EXPECTED_STRUCTURAL_LAMBDA_X
        ),
    }
    fixed_judgment = _fixed_judgment_from_conditions(fixed_conditions)
    # The expected value is reference information used only after independent
    # reconstruction.  Certificate validity depends on the evidence layers, not
    # on whether their correctly computed judgment happens to be Fixed.
    status = _STATUS_PASS if classification_ok and structural_ok else _STATUS_FAIL

    core: Dict[str, object] = {
        "core_certificate_id": CORE_ID,
        "package_label": PACKAGE_LABEL,
        "M": int(M),
        "b": int(M).bit_length() - 1,
        "maximum_simple_logical_cycle_length": int(bridge.get("maximum_simple_cycle_length", -1)),
        "exact_r_micrograph_state_count": int(micrograph["state_count"]),
        "exact_r_micrograph_microedge_count": int(micrograph["microedge_count"]),
        "exact_r_micrograph_hash_payload_fields": "M, states, edges",
        "exact_r_micrograph_sha256": str(micrograph["sha256"]),
        "exact_r_micrograph_state_set_independent_verify": "PENDING",
        "exact_r_micrograph_microedge_set_independent_verify": "PENDING",
        "exact_r_micrograph_transition_structure_independent_verify": "PENDING",
        "exact_r_micrograph_independent_verify": "PENDING",
        "derived_logical_r_graph_odd_state_count": int(logical_odd_states),
        "derived_logical_r_graph_logical_edge_count": int(logical_edges),
        "derived_logical_r_graph_hash_payload_fields": (
            "edge_id, src, dst, t, additional_division_cost, transformed_weight, micro_edge_ids"
        ),
        "derived_logical_r_graph_sha256": str(logical_hash),
        "derived_logical_r_graph_odd_state_set_independent_verify": "PENDING",
        "derived_logical_r_graph_logical_edge_set_independent_verify": "PENDING",
        "derived_logical_r_graph_microedge_sequence_independent_verify": "PENDING",
        "derived_logical_r_graph_division_label_independent_verify": "PENDING",
        "derived_logical_r_graph_hash_binding_independent_verify": "PENDING",
        "derived_logical_r_graph_independent_verify": "PENDING",
        "finite_circulation_bridge_graph_binding_independent_verify": "PENDING",
        "finite_circulation_bridge_length_bound_independent_verify": "PENDING",
        "finite_circulation_bridge_independent_verify": "PENDING",
        "minimum_bound_length_row_count": int(minimum_bound.get("length_row_count", -1)),
        "global_minimum_value_bound": int(minimum_bound.get("global_minimum_value_bound", -1)),
        "minimum_bound_global_argmax_lengths": list(
            minimum_bound.get("global_bound_attained_at_lengths", [])
        ),
        "minimum_bound_lengths_sha256": str(minimum_bound.get("lengths_csv_sha256", "")),
        "minimum_bound_rows_exact_and_maximal_independent_verify": "PENDING",
        "minimum_bound_global_bound_independent_verify": "PENDING",
        "minimum_bound_global_argmax_independent_verify": "PENDING",
        "minimum_bound_independent_verify": "PENDING",
        "expected_odd_minimum_candidates": (
            int(minimum_bound.get("global_minimum_value_bound", -1)) + 1
        ) // 2,
        "odd_minimum_candidates_audited": int(minimum_audit.get("total_odd_minimum_candidates", -1)),
        "odd_minimum_candidate_coverage_complete": (
            int(minimum_audit.get("total_odd_minimum_candidates", -1))
            == (int(minimum_bound.get("global_minimum_value_bound", -1)) + 1) // 2
        ),
        "odd_minimum_candidate_count_independent_verify": "PENDING",
        "minimum_candidate_blocks_independent_verify": "PENDING",
        "minimum_candidate_audit_independent_verify": "PENDING",
        "returned_to_start_count": int(minimum_audit.get("returned_to_start_count", -1)),
        "nontrivial_returned_candidates": int(minimum_audit.get("nontrivial_return_count", -1)),
        "descended_below_start_count": int(minimum_audit.get("descended_below_start_count", -1)),
        "no_return_within_max_length_count": int(minimum_audit.get("no_return_within_max_length_count", -1)),
        "trivial_loop": "1 -> 1, T = (2)",
        "terminal_counts_independent_verify": "PENDING",
        "returned_cycle_details_independent_verify": "PENDING",
        "nontrivial_return_zero_independent_verify": "PENDING",
        "trivial_loop_only_independent_verify": "PENDING",
        "certificate_scope": certificate_scope(int(M)),
        "proof_layer_count": 2,
        "artifact_path_policy": path_policy_record(),
        "child_artifacts": _child_artifact_records(out_dir),
        "layer_1_name": "complete positive-integer periodic-lift classification",
        "layer_1_status": classification.get("status"),
        "layer_1_independent_verify": classification_verify.get("verification_status"),
        "nontrivial_positive_integer_periodic_lifts_found": classification.get(
            "nontrivial_positive_integer_periodic_lifts_found"
        ),
        "trivial_1_loop_confirmed": classification.get("trivial_1_loop_confirmed"),
        "layer_2_name": "valid periodic-lift structural lambda",
        "layer_2_status": structural.get("status"),
        "layer_2_independent_verify": structural_verify.get("verification_status"),
        "valid_periodic_lift_structural_lambda_x": structural.get("structural_lambda_x_exact"),
        "expected_valid_periodic_lift_structural_lambda_x": EXPECTED_STRUCTURAL_LAMBDA_X,
        "valid_periodic_lift_structural_lambda_x_values": structural_values,
        "structural_lambda_x_fixed_judgment_conditions": fixed_conditions,
        "structural_lambda_x_fixed_judgment": fixed_judgment,
        "structural_lambda_x_fixed_judgment_independent_verify": "PENDING",
        "proof_uses_underlying_edge_deletion": False,
        "proof_uses_legacy_catalog_exclusion": False,
        "legacy_lp_reference_is_certificate_component": False,
        "legacy_lp_reference_is_proof_dependency": False,
        "legacy_lp_reference_is_hash_linked": False,
        "unrestricted_infinite_empirical_flow_lower_bound_claimed": False,
        "core_certificate_issued": status == _STATUS_PASS,
        "layer_1_certificate_issued": classification_ok,
        "layer_2_certificate_issued": structural_ok,
        "status": status,
    }
    add_creation_metadata(core, __program_id__)
    core["core_certificate_sha256"] = certificate_digest(core, "core_certificate_sha256")

    paths = certificate_paths(out_dir, int(M))
    cert_path = paths["json"]
    cert_path.write_text(json.dumps(core, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")

    report = [
        "# Appendix I self-describing portable two-layer core certificate",
        "",
        f"- package: `{PACKAGE_LABEL}`",
        f"- certificate modulus: `M={M}`",
        f"- status: **{status}**",
        "- path base: core-certificate directory",
        "- child paths: normalized POSIX-relative logical paths",
        "- child identity: role + logical path + size + SHA-256",
        "- absolute paths in certificate: forbidden",
        "- parent traversal / symlink artifacts: forbidden",
        "- Layer 1: positive-integer periodic lifts are the trivial 1-loop only",
        "- Layer 2: valid periodic-lift structural `lambda_x^str = 1`",
        f"- expected structural value: `lambda_x^str = {EXPECTED_STRUCTURAL_LAMBDA_X}`",
        f"- reconstructed structural-value set: `{structural_values}`",
        f"- structural-value Fixed judgment: **{fixed_judgment}**",
        "- underlying graph edge deletion used: `false`",
        "- legacy catalog exclusion used: `false`",
        "- legacy LP numerical comparison included in certificate: `false`",
        "- unrestricted infinite empirical-flow lower-bound claim: `false`",
        "",
        "## Child evidence logical paths",
    ]
    for role, record in core["child_artifacts"].items():
        report.append(f"- `{role}`: `{record['logical_path']}`")
    paths["report"].write_text(
        "\n".join(report) + "\n", encoding="utf-8"
    )

    write_human_readable_certificate(core, out_dir)
    write_certificate_hash_manifest(out_dir, int(M))
    return core

I.12.5 LIC_appendix_i_core_certificate_verifier.py

#!/usr/bin/env python3
"""Independent verifier for the portable two-layer Appendix-I core certificate.

Source metadata:
    File name: LIC_appendix_i_core_certificate_verifier.py
    Program version: X04a
    Source file version: 2.0.0
    Created: 2026-07-29 23:55:10 JST
    Last updated: 2026-08-02 16:32:00 JST

Function summary:
    Reconstructs and checks certificate schema, identities, child-artifact bindings, graph and
    audit facts, Layer 1 and Layer 2 results, structural-value judgment, and final status.

Remarks:
    Verification is performed independently of the core-certificate generator and fails closed
    on missing, malformed, or inconsistent evidence.
    Individual source-file versioning starts with this metadata revision. Earlier file-level
    changes are retained in package history but are not reconstructed as separate source-file
    versions.

Change history:
    - 2.0.0 / X04a / 2026-08-02 16:32:00 JST
      Replaced generator-side graph and core-certificate dependencies with verifier-owned mathematical reconstruction and certificate-output logic.
    - 1.1.0 / X03f / 2026-08-01 23:33:00 JST
      Added author-identity consistency verification across the core certificate and both certificate layers.
    - 1.0.1 / X03f / 2026-08-01 23:28:33 JST
      Updated the source metadata header for inclusion in the X03f Program package; executable logic is unchanged.
    - 1.0.0 / X03e / 2026-08-01 05:17:15 JST
      Added the standardized English source metadata header and established the
      initial individual source-file version baseline.
"""
from __future__ import annotations

import hashlib
import json
import re
from datetime import datetime
from zoneinfo import ZoneInfo
from pathlib import Path
from typing import Dict

from LIC_certificate_metadata import certificate_digest, finalize_certificate, metadata_checks, verification_record
from LIC_certificate_logical_paths import (
    EXPECTED_CHILD_PATHS,
    path_policy_record,
    resolve_logical_artifact,
    validate_child_artifact_records,
)
from LIC_complete_cycle_classification_verifier import verify_run as verify_complete_classification
from LIC_independent_ch3_math import micrograph_record, logical_graph_record
from LIC_structural_lambda_certificate_verifier import verify_run as verify_structural_lambda
from LIC_version import PACKAGE_LABEL, PACKAGE_VERSION
from LIC_status import STATUS_FAIL, STATUS_PASS

__program_id__ = "LIC_appendix_i_core_certificate_verifier"
__version__ = PACKAGE_VERSION
_STATUS_PASS = STATUS_PASS
_STATUS_FAIL = STATUS_FAIL
CORE_ID = "LIC-APPENDIX-I-CORE-CERTIFICATE-v7"
EXPECTED_STRUCTURAL_LAMBDA_X = "1"
FIXED_JUDGMENT_FIXED = "Fixed"
FIXED_JUDGMENT_NOT_FIXED = "NOT_FIXED"
FIXED_JUDGMENT_UNVERIFIED = "UNVERIFIED"


def certificate_scope(M: int) -> str:
    return (
        f"M={int(M)} derived logical R-graph simple extreme-cycle positive-integer "
        "periodic-lift complete classification, the resulting structural value, "
        "and the Fixed judgment against expected lambda_x^str=1"
    )


def certificate_paths(out_dir: Path, M: int) -> Dict[str, Path]:
    out_dir = Path(out_dir)
    stem = f"appendix_i_core_certificate_M{int(M)}"
    return {
        "json": out_dir / f"{stem}.json",
        "txt": out_dir / f"{stem}.txt",
        "report": out_dir / f"{stem}_report.md",
        "verify_summary": out_dir / f"{stem}_verify_summary.json",
        "sha256": out_dir / f"{stem}.sha256",
    }


def _jst(value: object) -> str:
    if not isinstance(value, str) or not value:
        return ""
    return datetime.fromisoformat(value).astimezone(ZoneInfo("Asia/Tokyo")).strftime(
        "%Y-%m-%d %H:%M:%S JST"
    )


def _canonical(obj: object) -> bytes:
    return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")


def _digest(obj: object) -> str:
    return hashlib.sha256(_canonical(obj)).hexdigest()


def _sha(path: Path) -> str:
    h = hashlib.sha256()
    with Path(path).open("rb") as f:
        for block in iter(lambda: f.read(1 << 20), b""):
            h.update(block)
    return h.hexdigest()



def write_certificate_hash_manifest(out_dir: Path, M: int) -> Path:
    paths = certificate_paths(out_dir, M)
    entries = []
    for key in ("json", "txt", "report", "verify_summary"):
        path = paths[key]
        if path.is_file():
            entries.append(f"{_sha(path)}  {path.name}")
    paths["sha256"].write_text("\n".join(entries) + "\n", encoding="ascii", newline="\n")
    return paths["sha256"]


def write_human_readable_certificate(core: Dict[str, object], out_dir: Path) -> None:
    """Write only the human-readable representation of the finite-check certificate.

    This output contains certificate fields and verified results only. It does not
    generate paper section headings, explanatory prose, theorem-condition mapping,
    theorem application, conclusions, or cross-references.
    """
    out_dir = Path(out_dir)
    fields = [
        ("finite-check certificate id", core.get("core_certificate_id")),
        ("package label", core.get("package_label")),
        ("b", core.get("b")),
        ("M", core.get("M")),
        ("N_M", core.get("maximum_simple_logical_cycle_length")),
        ("certificate author id", core.get("certificate_author_id")),
        ("certificate generation operator id", core.get("certificate_generation_operator_id")),
        ("certificate verification operator id", core.get("certificate_verification_operator_id")),
        ("certificate generator program id", core.get("certificate_generator_program_id")),
        ("certificate verifier program id", core.get("certificate_verifier_program_id")),
        ("finite-check certificate created at", _jst(core.get("certificate_created_at"))),
        ("finite-check certificate verified at", _jst(core.get("certificate_verified_at"))),
        ("finite-check certificate verification status", core.get("certificate_verification_status")),
        ("exact R-micrograph state count", core.get("exact_r_micrograph_state_count")),
        ("exact R-micrograph microedge count", core.get("exact_r_micrograph_microedge_count")),
        ("exact R-micrograph hash payload fields", core.get("exact_r_micrograph_hash_payload_fields")),
        ("exact R-micrograph SHA-256", core.get("exact_r_micrograph_sha256")),
        ("exact R-micrograph state-set verify", core.get("exact_r_micrograph_state_set_independent_verify")),
        ("exact R-micrograph microedge-set verify", core.get("exact_r_micrograph_microedge_set_independent_verify")),
        ("exact R-micrograph transition verify", core.get("exact_r_micrograph_transition_structure_independent_verify")),
        ("exact R-micrograph independent verify", core.get("exact_r_micrograph_independent_verify")),
        ("derived logical R-graph odd state count", core.get("derived_logical_r_graph_odd_state_count")),
        ("derived logical R-graph logical edge count", core.get("derived_logical_r_graph_logical_edge_count")),
        ("derived logical R-graph hash payload fields", core.get("derived_logical_r_graph_hash_payload_fields")),
        ("derived logical R-graph SHA-256", core.get("derived_logical_r_graph_sha256")),
        ("derived logical R-graph odd-state-set verify", core.get("derived_logical_r_graph_odd_state_set_independent_verify")),
        ("derived logical R-graph edge-set verify", core.get("derived_logical_r_graph_logical_edge_set_independent_verify")),
        ("logical-edge microedge-sequence verify", core.get("derived_logical_r_graph_microedge_sequence_independent_verify")),
        ("logical-edge division-label verify", core.get("derived_logical_r_graph_division_label_independent_verify")),
        ("derived logical R-graph hash-binding verify", core.get("derived_logical_r_graph_hash_binding_independent_verify")),
        ("derived logical R-graph independent verify", core.get("derived_logical_r_graph_independent_verify")),
        ("finite circulation bridge graph binding verify", core.get("finite_circulation_bridge_graph_binding_independent_verify")),
        ("finite circulation bridge length verify", core.get("finite_circulation_bridge_length_bound_independent_verify")),
        ("finite circulation bridge independent verify", core.get("finite_circulation_bridge_independent_verify")),
        ("minimum-bound length rows", core.get("minimum_bound_length_row_count")),
        ("global minimum-value bound B_M^global", core.get("global_minimum_value_bound")),
        ("global bound attained at L", ", ".join(str(x) for x in core.get("minimum_bound_global_argmax_lengths", []))),
        ("minimum-bound lengths SHA-256", core.get("minimum_bound_lengths_sha256")),
        ("all-length bounds exact/maximal verify", core.get("minimum_bound_rows_exact_and_maximal_independent_verify")),
        ("global minimum-value bound verify", core.get("minimum_bound_global_bound_independent_verify")),
        ("global-bound argmax verify", core.get("minimum_bound_global_argmax_independent_verify")),
        ("minimum-bound independent verify", core.get("minimum_bound_independent_verify")),
        ("odd minimum candidates expected", core.get("expected_odd_minimum_candidates")),
        ("odd minimum candidates audited", core.get("odd_minimum_candidates_audited")),
        ("odd minimum candidate coverage complete", "PASS" if core.get("odd_minimum_candidate_coverage_complete") is True else "FAIL"),
        ("candidate-count independent verify", core.get("odd_minimum_candidate_count_independent_verify")),
        ("candidate-blocks independent verify", core.get("minimum_candidate_blocks_independent_verify")),
        ("minimum-candidate audit independent verify", core.get("minimum_candidate_audit_independent_verify")),
        ("RETURNED_TO_START", core.get("returned_to_start_count")),
        ("nontrivial returned candidates", core.get("nontrivial_returned_candidates")),
        ("DESCENDED_BELOW_START", core.get("descended_below_start_count")),
        ("NO_RETURN_WITHIN_MAX_LENGTH", core.get("no_return_within_max_length_count")),
        ("trivial loop", core.get("trivial_loop")),
        ("terminal-counts independent verify", core.get("terminal_counts_independent_verify")),
        ("returned-cycle details independent verify", core.get("returned_cycle_details_independent_verify")),
        ("nontrivial-return-zero independent verify", core.get("nontrivial_return_zero_independent_verify")),
        ("trivial-loop-only independent verify", core.get("trivial_loop_only_independent_verify")),
        ("Layer 1 independent verify", core.get("layer_1_independent_verify")),
        ("Layer 2 independent verify", core.get("layer_2_independent_verify")),
        ("structural value lambda_x^str", core.get("valid_periodic_lift_structural_lambda_x")),
        ("expected structural value lambda_x^str", core.get("expected_valid_periodic_lift_structural_lambda_x")),
        (
            "structural value lambda_x^str set",
            "{" + ", ".join(str(x) for x in core.get("valid_periodic_lift_structural_lambda_x_values", [])) + "}",
        ),
        ("structural value lambda_x^str fixed judgment", core.get("structural_lambda_x_fixed_judgment")),
        (
            "structural value fixed judgment independent verify",
            core.get("structural_lambda_x_fixed_judgment_independent_verify"),
        ),
        ("core certificate independent verify", core.get("certificate_verification_status")),
        ("core certificate verified at", _jst(core.get("certificate_verified_at"))),
    ]
    label_width = max(len(label) for label, _ in fields)
    body = [f"{label:<{label_width}} : {value}" for label, value in fields]
    paths = certificate_paths(out_dir, int(core.get("M")))
    txt_path = paths["txt"]
    txt_path.write_text("\n".join(body) + "\n", encoding="utf-8", newline="\n")
    write_certificate_hash_manifest(out_dir, int(core.get("M")))




def _fixed_judgment_from_conditions(conditions: Dict[str, bool]) -> str:
    prerequisite_names = (
        "candidate_audit_range_complete",
        "all_candidates_decided",
        "layer_1_complete_classification_independent_verify",
        "valid_extreme_structure_set_complete",
        "layer_2_all_structural_values_reconstructed",
    )
    if not all(conditions.get(name) is True for name in prerequisite_names):
        return FIXED_JUDGMENT_UNVERIFIED
    if (
        conditions.get("reconstructed_structural_value_set_is_singleton_expected") is True
        and conditions.get("reconstructed_value_matches_expected") is True
    ):
        return FIXED_JUDGMENT_FIXED
    return FIXED_JUDGMENT_NOT_FIXED

def _failed_result(run_dir: Path, cert: Dict[str, object], checks: Dict[str, bool], error: str) -> Dict[str, object]:
    M = int(cert.get("M", -1))
    result = {
        "package_label": PACKAGE_LABEL,
        "M": cert.get("M"),
        "verification_status": "FAIL",
        "overall_status": _STATUS_FAIL,
        "checks": checks,
        **verification_record(cert),
        "path_validation_error": error,
    }
    certificate_paths(run_dir, M)["verify_summary"].write_text(
        json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
    )
    write_certificate_hash_manifest(run_dir, M)
    return result


def _resolve_certificate_path(run_dir: Path, M: int | None) -> Path:
    run_dir = Path(run_dir)
    if M is not None:
        path = certificate_paths(run_dir, int(M))["json"]
        if not path.is_file():
            raise FileNotFoundError(path)
        return path
    matches = sorted(
        path for path in run_dir.glob("appendix_i_core_certificate_M*.json")
        if re.fullmatch(r"appendix_i_core_certificate_M\d+\.json", path.name)
    )
    if len(matches) != 1:
        raise ValueError(
            "exactly one M-specific core certificate is required when --M is omitted"
        )
    return matches[0]


def verify_run(run_dir: Path, M: int | None = None) -> Dict[str, object]:
    run_dir = Path(run_dir)
    cert_path = _resolve_certificate_path(run_dir, M)
    cert = json.loads(cert_path.read_text(encoding="utf-8"))
    M = int(cert.get("M", -1))

    path_checks = {
        "path_policy_ok": cert.get("artifact_path_policy") == path_policy_record(),
        "child_artifact_records_ok": False,
        "logical_paths_resolve_inside_run_dir": False,
        "logical_paths_are_exact_normative_roles": False,
        "no_absolute_or_parent_traversal_paths": False,
        "no_symlink_artifacts": False,
    }
    try:
        records = validate_child_artifact_records(cert.get("child_artifacts"))
        resolved = {
            role: resolve_logical_artifact(run_dir, record["logical_path"])
            for role, record in records.items()
        }
        path_checks.update(
            {
                "child_artifact_records_ok": True,
                "logical_paths_resolve_inside_run_dir": True,
                "logical_paths_are_exact_normative_roles": all(
                    records[role]["logical_path"] == expected
                    for role, expected in EXPECTED_CHILD_PATHS.items()
                ),
                "no_absolute_or_parent_traversal_paths": True,
                "no_symlink_artifacts": True,
            }
        )
    except (ValueError, OSError, FileNotFoundError) as exc:
        return _failed_result(run_dir, cert, path_checks, str(exc))

    classification_cert_path = resolved["layer_1_certificate"]
    classification_verify_path = resolved["layer_1_verify"]
    structural_cert_path = resolved["layer_2_certificate"]
    structural_verify_path = resolved["layer_2_verify"]
    classification_dir = classification_cert_path.parent
    structural_dir = structural_cert_path.parent

    # The independent child verifiers rewrite their verify summaries. Their
    # logical paths are certificate-declared and their resulting hashes are then
    # compared with the hashes bound into the core certificate.
    cv = verify_complete_classification(classification_dir)
    sv = verify_structural_lambda(structural_dir, classification_dir)
    classification = json.loads(classification_cert_path.read_text(encoding="utf-8"))
    structural = json.loads(structural_cert_path.read_text(encoding="utf-8"))
    bridge = json.loads(
        (classification_dir / "finite_lp_cycle_bridge" / "finite_lp_cycle_bridge_certificate.json").read_text(encoding="utf-8")
    )
    bridge_verify = json.loads(
        (classification_dir / "finite_lp_cycle_bridge" / "finite_lp_cycle_bridge_verify_summary.json").read_text(encoding="utf-8")
    )
    minimum_bound = json.loads(
        (classification_dir / "minimum_candidate_audit" / "minimum_bound" / "cycle_minimum_bound_certificate.json").read_text(encoding="utf-8")
    )
    minimum_bound_verify = json.loads(
        (classification_dir / "minimum_candidate_audit" / "minimum_bound" / "cycle_minimum_bound_verify_summary.json").read_text(encoding="utf-8")
    )
    minimum_audit = json.loads(
        (classification_dir / "minimum_candidate_audit" / "cycle_minimum_candidate_audit_summary.json").read_text(encoding="utf-8")
    )
    minimum_audit_verify = json.loads(
        (classification_dir / "minimum_candidate_audit" / "cycle_minimum_candidate_audit_verify_summary.json").read_text(encoding="utf-8")
    )
    M = int(cert.get("M", -1))
    micrograph = micrograph_record(M)
    independent_logical = logical_graph_record(M)
    logical_hash = str(independent_logical["sha256"])
    logical_odd_states = int(independent_logical["odd_state_count"])
    logical_edges = int(independent_logical["logical_edge_count"])

    bridge_checks = bridge_verify.get("checks", {})
    minimum_bound_checks = minimum_bound_verify.get("checks", {})
    minimum_audit_checks = minimum_audit_verify.get("checks", {})

    micrograph_state_set_ok = (
        int(cert.get("exact_r_micrograph_state_count", -1)) == int(micrograph["state_count"])
        and cert.get("exact_r_micrograph_sha256") == micrograph["sha256"]
    )
    micrograph_microedge_set_ok = (
        int(cert.get("exact_r_micrograph_microedge_count", -1)) == int(micrograph["microedge_count"])
        and cert.get("exact_r_micrograph_sha256") == micrograph["sha256"]
    )
    micrograph_transition_structure_ok = cert.get("exact_r_micrograph_sha256") == micrograph["sha256"]

    logical_graph_hash_ok = (
        cert.get("derived_logical_r_graph_sha256") == logical_hash
        and bridge.get("logical_graph_sha256") == logical_hash
        and minimum_bound.get("logical_graph_sha256") == logical_hash
        and minimum_audit.get("logical_graph_sha256") == logical_hash
    )
    logical_odd_state_set_ok = (
        int(cert.get("derived_logical_r_graph_odd_state_count", -1)) == logical_odd_states
        and logical_graph_hash_ok
    )
    logical_edge_set_ok = (
        int(cert.get("derived_logical_r_graph_logical_edge_count", -1)) == logical_edges
        and logical_graph_hash_ok
    )
    logical_microedge_sequence_ok = logical_graph_hash_ok
    logical_division_label_ok = logical_graph_hash_ok

    bridge_graph_binding_ok = (
        bridge_verify.get("verification_status") == "PASS"
        and bridge_checks.get("graph_binding_ok") is True
    )
    bridge_length_bound_ok = (
        bridge_verify.get("verification_status") == "PASS"
        and bridge_checks.get("length_bound_ok") is True
        and int(bridge.get("maximum_simple_cycle_length", -1)) == M // 2
    )

    minimum_bound_rows_ok = (
        minimum_bound_verify.get("verification_status") == "PASS"
        and minimum_bound_checks.get("bound_rows_exact_and_maximal") is True
    )
    minimum_bound_global_ok = (
        minimum_bound_verify.get("verification_status") == "PASS"
        and minimum_bound_checks.get("global_bound_ok") is True
    )
    minimum_bound_argmax_ok = (
        minimum_bound_verify.get("verification_status") == "PASS"
        and minimum_bound_checks.get("global_bound_argmax_ok") is True
    )
    minimum_bound_all_ok = (
        minimum_bound_rows_ok and minimum_bound_global_ok and minimum_bound_argmax_ok
        and minimum_bound_checks.get("bound_files_hash_ok") is True
    )

    expected_candidates = (int(minimum_bound.get("global_minimum_value_bound", -1)) + 1) // 2
    candidate_count_ok = (
        minimum_audit_verify.get("verification_status") == "PASS"
        and minimum_audit_checks.get("candidate_total_ok") is True
        and int(minimum_audit.get("total_odd_minimum_candidates", -1)) == expected_candidates
    )
    candidate_blocks_ok = (
        minimum_audit_verify.get("verification_status") == "PASS"
        and minimum_audit_checks.get("blocks_exact_match") is True
        and minimum_audit_checks.get("blocks_hash_ok") is True
    )
    minimum_candidate_audit_ok = (
        candidate_count_ok and candidate_blocks_ok
        and minimum_audit_checks.get("final_evidence_hash_ok") is True
        and minimum_audit_checks.get("certificate_gate_ok") is True
    )
    terminal_counts_ok = (
        minimum_audit_verify.get("verification_status") == "PASS"
        and minimum_audit_checks.get("terminal_counts_ok") is True
    )
    returned_cycle_details_ok = (
        minimum_audit_verify.get("verification_status") == "PASS"
        and minimum_audit_checks.get("returned_cycles_ok") is True
    )
    nontrivial_return_zero_ok = (
        minimum_audit_verify.get("verification_status") == "PASS"
        and minimum_audit_checks.get("nontrivial_return_zero") is True
    )
    trivial_loop_only_ok = (
        terminal_counts_ok and returned_cycle_details_ok and nontrivial_return_zero_ok
        and int(minimum_audit.get("returned_to_start_count", -1)) == 1
        and int(minimum_audit.get("nontrivial_return_count", -1)) == 0
        and int(minimum_audit.get("no_return_within_max_length_count", -1)) == 0
        and minimum_audit.get("returned_cycle_summaries") == [
            {"minimum_candidate": 1, "steps": 1, "sum_T": 2, "max_value_bit_length": 1}
        ]
    )

    reconstructed_structural_values = []
    structural_exact = structural.get("structural_lambda_x_exact")
    if (
        structural.get("valid_periodic_lift_extreme_structures") == 1
        and isinstance(structural_exact, str)
        and structural_exact
    ):
        reconstructed_structural_values = [structural_exact]
    returned_count = int(minimum_audit.get("returned_to_start_count", -1))
    descended_count = int(minimum_audit.get("descended_below_start_count", -1))
    undecided_count = int(minimum_audit.get("no_return_within_max_length_count", -1))
    audited_candidates = int(minimum_audit.get("total_odd_minimum_candidates", -1))
    fixed_conditions = {
        "candidate_audit_range_complete": (
            minimum_audit_verify.get("verification_status") == "PASS"
            and candidate_count_ok
            and candidate_blocks_ok
        ),
        "all_candidates_decided": (
            minimum_audit_verify.get("verification_status") == "PASS"
            and terminal_counts_ok
            and undecided_count == 0
            and returned_count + descended_count + undecided_count == audited_candidates
        ),
        "layer_1_complete_classification_independent_verify": (
            cv.get("verification_status") == "PASS"
            and classification.get("status") == STATUS_PASS
        ),
        "valid_extreme_structure_set_complete": (
            cv.get("verification_status") == "PASS"
            and classification.get("pass_trivial_only") is True
            and int(classification.get("positive_integer_periodic_lifts_found", -1)) == 1
            and int(classification.get("nontrivial_positive_integer_periodic_lifts_found", -1)) == 0
            and classification.get("trivial_1_loop_confirmed") is True
        ),
        "layer_2_all_structural_values_reconstructed": (
            sv.get("verification_status") == "PASS"
            and structural.get("status") == STATUS_PASS
            and int(structural.get("valid_periodic_lift_extreme_structures", -1))
            == len(reconstructed_structural_values)
            == 1
        ),
        "reconstructed_structural_value_set_is_singleton_expected": (
            reconstructed_structural_values == [EXPECTED_STRUCTURAL_LAMBDA_X]
        ),
        "reconstructed_value_matches_expected": (
            structural_exact == EXPECTED_STRUCTURAL_LAMBDA_X
        ),
    }
    expected_fixed_judgment = _fixed_judgment_from_conditions(fixed_conditions)
    fixed_judgment_fields_ok = (
        cert.get("expected_valid_periodic_lift_structural_lambda_x")
        == EXPECTED_STRUCTURAL_LAMBDA_X
        and cert.get("valid_periodic_lift_structural_lambda_x_values")
        == reconstructed_structural_values
        and cert.get("structural_lambda_x_fixed_judgment_conditions")
        == fixed_conditions
        and cert.get("structural_lambda_x_fixed_judgment")
        == expected_fixed_judgment
    )

    evidence_status_values = {
        "exact_r_micrograph_state_set_independent_verify": "PASS" if micrograph_state_set_ok else "FAIL",
        "exact_r_micrograph_microedge_set_independent_verify": "PASS" if micrograph_microedge_set_ok else "FAIL",
        "exact_r_micrograph_transition_structure_independent_verify": "PASS" if micrograph_transition_structure_ok else "FAIL",
        "exact_r_micrograph_independent_verify": "PASS" if (
            micrograph_state_set_ok and micrograph_microedge_set_ok and micrograph_transition_structure_ok
        ) else "FAIL",
        "derived_logical_r_graph_odd_state_set_independent_verify": "PASS" if logical_odd_state_set_ok else "FAIL",
        "derived_logical_r_graph_logical_edge_set_independent_verify": "PASS" if logical_edge_set_ok else "FAIL",
        "derived_logical_r_graph_microedge_sequence_independent_verify": "PASS" if logical_microedge_sequence_ok else "FAIL",
        "derived_logical_r_graph_division_label_independent_verify": "PASS" if logical_division_label_ok else "FAIL",
        "derived_logical_r_graph_hash_binding_independent_verify": "PASS" if logical_graph_hash_ok else "FAIL",
        "derived_logical_r_graph_independent_verify": "PASS" if (
            logical_odd_state_set_ok and logical_edge_set_ok and logical_microedge_sequence_ok
            and logical_division_label_ok and logical_graph_hash_ok
        ) else "FAIL",
        "finite_circulation_bridge_graph_binding_independent_verify": "PASS" if bridge_graph_binding_ok else "FAIL",
        "finite_circulation_bridge_length_bound_independent_verify": "PASS" if bridge_length_bound_ok else "FAIL",
        "finite_circulation_bridge_independent_verify": "PASS" if (
            bridge_graph_binding_ok and bridge_length_bound_ok
        ) else "FAIL",
        "minimum_bound_rows_exact_and_maximal_independent_verify": "PASS" if minimum_bound_rows_ok else "FAIL",
        "minimum_bound_global_bound_independent_verify": "PASS" if minimum_bound_global_ok else "FAIL",
        "minimum_bound_global_argmax_independent_verify": "PASS" if minimum_bound_argmax_ok else "FAIL",
        "minimum_bound_independent_verify": "PASS" if minimum_bound_all_ok else "FAIL",
        "odd_minimum_candidate_count_independent_verify": "PASS" if candidate_count_ok else "FAIL",
        "minimum_candidate_blocks_independent_verify": "PASS" if candidate_blocks_ok else "FAIL",
        "minimum_candidate_audit_independent_verify": "PASS" if minimum_candidate_audit_ok else "FAIL",
        "terminal_counts_independent_verify": "PASS" if terminal_counts_ok else "FAIL",
        "returned_cycle_details_independent_verify": "PASS" if returned_cycle_details_ok else "FAIL",
        "nontrivial_return_zero_independent_verify": "PASS" if nontrivial_return_zero_ok else "FAIL",
        "trivial_loop_only_independent_verify": "PASS" if trivial_loop_only_ok else "FAIL",
        "structural_lambda_x_fixed_judgment_independent_verify": (
            "PASS" if fixed_judgment_fields_ok else "FAIL"
        ),
    }
    evidence_status_fields_valid = all(
        cert.get(field) in {"PENDING", expected}
        for field, expected in evidence_status_values.items()
    )

    checks = {
        **metadata_checks(cert, "LIC_appendix_i_core_certificate"),
        **path_checks,
        "package_label_ok": cert.get("package_label") == PACKAGE_LABEL,
        "layer_certificate_author_ids_match": (
            cert.get("certificate_author_id")
            == classification.get("certificate_author_id")
            == structural.get("certificate_author_id")
        ),
        "id_ok": cert.get("core_certificate_id") == CORE_ID,
        "digest_ok": cert.get("core_certificate_sha256") == certificate_digest(cert, "core_certificate_sha256"),
        "M_and_b_ok": int(cert.get("M", -1)) == M and int(cert.get("b", -1)) == M.bit_length() - 1,
        "scope_ok": cert.get("certificate_scope") == certificate_scope(M),
        "two_layer_structure_ok": int(cert.get("proof_layer_count", -1)) == 2,
        "layer_1_verify_pass": cv.get("verification_status") == "PASS",
        "layer_2_verify_pass": sv.get("verification_status") == "PASS",
        "trivial_only_ok": (
            classification.get("pass_trivial_only") is True
            and int(classification.get("nontrivial_positive_integer_periodic_lifts_found", -1)) == 0
            and cert.get("trivial_1_loop_confirmed") is True
        ),
        "structural_lambda_ok": (
            structural.get("structural_lambda_x_exact")
            == cert.get("valid_periodic_lift_structural_lambda_x")
            == "1"
        ),
        "expected_structural_lambda_specification_ok": (
            cert.get("expected_valid_periodic_lift_structural_lambda_x")
            == EXPECTED_STRUCTURAL_LAMBDA_X
        ),
        "structural_lambda_value_set_ok": (
            cert.get("valid_periodic_lift_structural_lambda_x_values")
            == reconstructed_structural_values
        ),
        "structural_lambda_fixed_judgment_conditions_ok": (
            cert.get("structural_lambda_x_fixed_judgment_conditions")
            == fixed_conditions
        ),
        "structural_lambda_fixed_judgment_ok": (
            cert.get("structural_lambda_x_fixed_judgment")
            == expected_fixed_judgment
        ),
        "no_edge_deletion_ok": (
            cert.get("proof_uses_underlying_edge_deletion") is False
            and cert.get("proof_uses_legacy_catalog_exclusion") is False
            and structural.get("underlying_graph_edge_deletion_used") is False
            and structural.get("legacy_catalog_exclusion_used") is False
        ),
        "legacy_reference_separated_ok": (
            cert.get("legacy_lp_reference_is_certificate_component") is False
            and cert.get("legacy_lp_reference_is_proof_dependency") is False
            and cert.get("legacy_lp_reference_is_hash_linked") is False
        ),
        "no_unrestricted_flow_claim_ok": (
            cert.get("unrestricted_infinite_empirical_flow_lower_bound_claimed") is False
        ),
        "issuance_gate_ok": (
            cert.get("core_certificate_issued") is True
            and cert.get("layer_1_certificate_issued") is True
            and cert.get("layer_2_certificate_issued") is True
        ),
        "child_sizes_ok": all(
            records[role]["size_bytes"] == resolved[role].stat().st_size
            for role in EXPECTED_CHILD_PATHS
        ),
        "child_hashes_ok": all(
            records[role]["sha256"] == _sha(resolved[role])
            for role in EXPECTED_CHILD_PATHS
        ),
        "certificate_evidence_values_ok": (
            int(cert.get("maximum_simple_logical_cycle_length", -1))
            == int(bridge.get("maximum_simple_cycle_length", -2))
            == M // 2
            and int(cert.get("exact_r_micrograph_state_count", -1)) == int(micrograph["state_count"])
            and int(cert.get("exact_r_micrograph_microedge_count", -1)) == int(micrograph["microedge_count"])
            and cert.get("exact_r_micrograph_hash_payload_fields") == "M, states, edges"
            and cert.get("exact_r_micrograph_sha256") == micrograph["sha256"]
            and int(cert.get("derived_logical_r_graph_odd_state_count", -1)) == logical_odd_states
            and int(cert.get("derived_logical_r_graph_logical_edge_count", -1)) == logical_edges
            and cert.get("derived_logical_r_graph_hash_payload_fields")
            == "edge_id, src, dst, t, additional_division_cost, transformed_weight, micro_edge_ids"
            and cert.get("derived_logical_r_graph_sha256") == logical_hash
            and int(cert.get("minimum_bound_length_row_count", -1)) == int(minimum_bound.get("length_row_count", -2))
            and int(cert.get("global_minimum_value_bound", -1)) == int(minimum_bound.get("global_minimum_value_bound", -2))
            and cert.get("minimum_bound_global_argmax_lengths") == minimum_bound.get("global_bound_attained_at_lengths")
            and cert.get("minimum_bound_lengths_sha256") == minimum_bound.get("lengths_csv_sha256")
            and int(cert.get("expected_odd_minimum_candidates", -1)) == expected_candidates
            and int(cert.get("odd_minimum_candidates_audited", -1)) == int(minimum_audit.get("total_odd_minimum_candidates", -2))
            and cert.get("odd_minimum_candidate_coverage_complete") is True
            and int(cert.get("returned_to_start_count", -1)) == int(minimum_audit.get("returned_to_start_count", -2))
            and int(cert.get("nontrivial_returned_candidates", -1)) == int(minimum_audit.get("nontrivial_return_count", -2))
            and int(cert.get("descended_below_start_count", -1)) == int(minimum_audit.get("descended_below_start_count", -2))
            and int(cert.get("no_return_within_max_length_count", -1)) == int(minimum_audit.get("no_return_within_max_length_count", -2))
            and cert.get("trivial_loop") == "1 -> 1, T = (2)"
        ),
        "certificate_evidence_status_fields_valid": evidence_status_fields_valid,
        "status_ok": cert.get("status") == _STATUS_PASS,
    }
    ok = all(checks.values())
    status = "PASS" if ok else "FAIL"
    cert.update(evidence_status_values)
    cert["core_certificate_sha256"] = certificate_digest(cert, "core_certificate_sha256")
    cert_path.write_text(json.dumps(cert, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    cert = finalize_certificate(cert_path, cert, verifier_program_id=__program_id__, verification_status=status, digest_field="core_certificate_sha256")
    write_human_readable_certificate(cert, run_dir)
    result = {
        "package_label": PACKAGE_LABEL,
        "M": cert.get("M"),
        "verification_status": status,
        "overall_status": cert.get("status") if ok else _STATUS_FAIL,
        "expected_structural_lambda_x": cert.get("expected_valid_periodic_lift_structural_lambda_x"),
        "reconstructed_structural_lambda_x_values": cert.get("valid_periodic_lift_structural_lambda_x_values"),
        "structural_lambda_x_fixed_judgment": cert.get("structural_lambda_x_fixed_judgment"),
        "structural_lambda_x_fixed_judgment_independent_verify": cert.get(
            "structural_lambda_x_fixed_judgment_independent_verify"
        ),
        "checks": checks,
        **verification_record(cert),
        "verified_child_logical_paths": {
            role: records[role]["logical_path"] for role in EXPECTED_CHILD_PATHS
        },
        "independent_mathematical_reconstruction_program_id": "LIC_independent_ch3_math",
        "independent_logical_graph_semantic_sha256": independent_logical["semantic_sha256"],
        "verified_certificate_sha256": _sha(cert_path),
    }
    certificate_paths(run_dir, M)["verify_summary"].write_text(
        json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
    )
    write_certificate_hash_manifest(run_dir, M)
    return result

I.12.6 LIC_certificate_logical_paths.py

#!/usr/bin/env python3
"""Logical-path policy for portable Appendix-I certificate artifacts.

Source metadata:
    File name: LIC_certificate_logical_paths.py
    Program version: X04a
    Source file version: 1.0.2
    Created: 2026-07-23 15:56:26 JST
    Last updated: 2026-08-02 16:32:00 JST

Function summary:
    Defines portable relative-path records, validates path safety, validates child-artifact
    records, and resolves certificate-relative artifact locations.

Remarks:
    Absolute paths, parent-directory traversal, and unsafe logical artifact references are
    rejected.
    Individual source-file versioning starts with this metadata revision. Earlier file-level
    changes are retained in package history but are not reconstructed as separate source-file
    versions.

Change history:
    - 1.0.2 / X04a / 2026-08-02 16:32:00 JST
      Updated X04a Program-membership metadata; executable logic is unchanged.
    - 1.0.1 / X03f / 2026-08-01 23:28:33 JST
      Updated the source metadata header for inclusion in the X03f Program package; executable logic is unchanged.
    - 1.0.0 / X03e / 2026-08-01 05:17:15 JST
      Added the standardized English source metadata header and established the
      initial individual source-file version baseline.
"""
from __future__ import annotations

import re
from pathlib import Path, PurePosixPath
from typing import Dict, Mapping

from LIC_version import PACKAGE_VERSION

__program_id__ = "LIC_certificate_logical_paths"
__version__ = PACKAGE_VERSION

PATH_POLICY_ID = "LIC-CORE-CERTIFICATE-LOGICAL-RELATIVE-PATH-POLICY-v1"
PATH_BASE = "core_certificate_directory"
PATH_FORMAT = "POSIX-relative"

EXPECTED_CHILD_PATHS: Dict[str, str] = {
    "layer_1_certificate": (
        "layer1_periodic_lift_classification/"
        "complete_cycle_classification_certificate.json"
    ),
    "layer_1_verify": (
        "layer1_periodic_lift_classification/"
        "complete_cycle_classification_verify_summary.json"
    ),
    "layer_2_certificate": (
        "layer2_structural_lambda/structural_lambda_certificate.json"
    ),
    "layer_2_verify": (
        "layer2_structural_lambda/structural_lambda_verify_summary.json"
    ),
}

_WINDOWS_DRIVE_RE = re.compile(r"^[A-Za-z]:")
_URI_SCHEME_RE = re.compile(r"^[A-Za-z][A-Za-z0-9+.-]*:")


def path_policy_record() -> Dict[str, object]:
    """Return the normative portable-path policy stored in the certificate."""
    return {
        "policy_id": PATH_POLICY_ID,
        "base": PATH_BASE,
        "format": PATH_FORMAT,
        "absolute_paths_allowed": False,
        "parent_traversal_allowed": False,
        "backslash_allowed": False,
        "symlink_artifacts_allowed": False,
        "normalized_posix_form_required": True,
    }


def validate_logical_relative_path(value: object) -> str:
    """Validate and return a normalized package-portable logical path.

    The accepted syntax is a non-empty normalized POSIX relative path. Absolute
    paths, Windows drive paths, URI-like values, backslashes, ``.``/``..``
    components, duplicate separators and trailing separators are rejected.
    """
    if not isinstance(value, str) or not value:
        raise ValueError("logical path must be a non-empty string")
    if "\x00" in value:
        raise ValueError("logical path contains NUL")
    if "\\" in value:
        raise ValueError("logical path must use POSIX '/' separators")
    if value.startswith("/") or value.startswith("//"):
        raise ValueError("absolute logical path is forbidden")
    if _WINDOWS_DRIVE_RE.match(value):
        raise ValueError("Windows drive path is forbidden")
    if _URI_SCHEME_RE.match(value):
        raise ValueError("URI-like logical path is forbidden")

    pure = PurePosixPath(value)
    parts = pure.parts
    if not parts or any(part in ("", ".", "..") for part in parts):
        raise ValueError("logical path contains empty, '.' or '..' component")
    normalized = pure.as_posix()
    if normalized != value:
        raise ValueError("logical path is not in normalized POSIX form")
    return normalized


def validate_child_artifact_records(records: object) -> Dict[str, Mapping[str, object]]:
    """Validate the complete child-artifact mapping and exact logical roles."""
    if not isinstance(records, dict):
        raise ValueError("child_artifacts must be an object")
    if set(records) != set(EXPECTED_CHILD_PATHS):
        raise ValueError("child_artifacts roles do not match the normative role set")

    result: Dict[str, Mapping[str, object]] = {}
    for role, expected_path in EXPECTED_CHILD_PATHS.items():
        record = records.get(role)
        if not isinstance(record, dict):
            raise ValueError(f"child artifact record {role!r} must be an object")
        if set(record) != {"logical_path", "sha256", "size_bytes"}:
            raise ValueError(f"child artifact record {role!r} has unexpected fields")
        logical_path = validate_logical_relative_path(record.get("logical_path"))
        if logical_path != expected_path:
            raise ValueError(f"child artifact {role!r} has unexpected logical path")
        digest = record.get("sha256")
        if not isinstance(digest, str) or not re.fullmatch(r"[0-9a-f]{64}", digest):
            raise ValueError(f"child artifact {role!r} has invalid SHA-256")
        size_bytes = record.get("size_bytes")
        if not isinstance(size_bytes, int) or isinstance(size_bytes, bool) or size_bytes < 0:
            raise ValueError(f"child artifact {role!r} has invalid size_bytes")
        result[role] = record
    return result


def resolve_logical_artifact(root: Path, logical_path: object) -> Path:
    """Resolve a logical path below ``root`` without allowing path escape.

    Every existing component must be a real directory/file, not a symlink. This
    makes the logical path and the hashed file identity unambiguous after moving
    or extracting the package.
    """
    normalized = validate_logical_relative_path(logical_path)
    root = Path(root)
    root_resolved = root.resolve(strict=True)
    candidate = root.joinpath(*PurePosixPath(normalized).parts)

    # Reject symlinks in every component, including the final artifact.
    current = root
    for part in PurePosixPath(normalized).parts:
        current = current / part
        if current.is_symlink():
            raise ValueError("symlink artifact or parent is forbidden")

    candidate_resolved = candidate.resolve(strict=True)
    try:
        candidate_resolved.relative_to(root_resolved)
    except ValueError as exc:
        raise ValueError("logical path escapes the certificate directory") from exc
    if not candidate_resolved.is_file():
        raise ValueError("logical path does not identify a regular file")
    return candidate_resolved

I.12.7 LIC_certificate_metadata.py

#!/usr/bin/env python3
"""Shared metadata and digest helpers for CTV certificates.

Source metadata:
    File name: LIC_certificate_metadata.py
    Program version: X04a
    Source file version: 1.1.1
    Created: 2026-07-26 02:55:00 JST
    Last updated: 2026-08-02 16:32:00 JST

Function summary:
    Provides JST timestamps, UUID handling, operator context, canonical JSON serialization,
    SHA-256 helpers, certificate metadata validation, finalization, and verification records.

Remarks:
    Canonical serialization and identity checks are shared by generators and verifiers to keep
    certificate metadata consistent.
    Individual source-file versioning starts with this metadata revision. Earlier file-level
    changes are retained in package history but are not reconstructed as separate source-file
    versions.

Change history:
    - 1.1.1 / X04a / 2026-08-02 16:32:00 JST
      Updated X04a Program-membership metadata; executable logic is unchanged.
    - 1.1.0 / X03f / 2026-08-01 23:28:33 JST
      Removed the fixed certificate-author UUID, added run-scoped author identity resolution, and changed metadata validation to accept any canonical UUID.
    - 1.0.0 / X03e / 2026-08-01 05:17:15 JST
      Added the standardized English source metadata header and established the
      initial individual source-file version baseline.
"""
from __future__ import annotations

import hashlib
import json
import os
import uuid
from datetime import datetime
from pathlib import Path
from typing import Dict

from LIC_version import PACKAGE_VERSION

__program_id__ = "LIC_certificate_metadata"
__version__ = PACKAGE_VERSION

CERTIFICATE_METADATA_SCHEMA = "CTV-CERTIFICATE-METADATA-v3"
AUTHOR_ID_ENV = "CTV_AUTHOR_ID"
AUTHOR_ID_SOURCE_ENV = "CTV_AUTHOR_ID_SOURCE"
OPERATOR_ID_ENV = "CTV_OPERATOR_ID"
OPERATOR_ID_SOURCE_ENV = "CTV_OPERATOR_ID_SOURCE"
_IDENTITY_SOURCES = {"user-specified", "auto-generated", "operator-derived", "inherited"}

_VERIFICATION_FIELDS = {
    "certificate_verifier_program_id",
    "certificate_verification_operator_id",
    "certificate_verification_operator_id_source",
    "certificate_verified_at",
    "certificate_verification_status",
    "verified_payload_sha256",
}


def iso_now() -> str:
    """Return an RFC 3339 timestamp with the local UTC offset, to seconds."""
    return datetime.now().astimezone().isoformat(timespec="seconds")


def canonical_uuid(value: str) -> str:
    """Validate and normalize a UUID/GUID string to canonical lowercase form."""
    try:
        parsed = uuid.UUID(str(value).strip())
    except (ValueError, AttributeError, TypeError) as exc:
        raise ValueError(f"invalid UUID/GUID: {value!r}") from exc
    return str(parsed)


def set_operator_context(operator_id: str, source: str) -> tuple[str, str]:
    """Set the process-wide operator context inherited by all child processes."""
    normalized = canonical_uuid(operator_id)
    normalized_source = str(source)
    if normalized_source not in _IDENTITY_SOURCES:
        raise ValueError(f"invalid operator ID source: {source!r}")
    os.environ[OPERATOR_ID_ENV] = normalized
    os.environ[OPERATOR_ID_SOURCE_ENV] = normalized_source
    return normalized, normalized_source


def resolve_operator_identity(explicit_operator_id: str | None = None) -> tuple[str, str]:
    """Resolve a run-scoped operator UUID.

    Resolution order:
      1. explicit command option -> user-specified;
      2. inherited process environment -> inherited/original source;
      3. one-time UUID v4 -> auto-generated.
    """
    if explicit_operator_id:
        return set_operator_context(explicit_operator_id, "user-specified")
    inherited = os.environ.get(OPERATOR_ID_ENV)
    if inherited:
        inherited_source = os.environ.get(OPERATOR_ID_SOURCE_ENV, "inherited")
        if inherited_source not in _IDENTITY_SOURCES:
            inherited_source = "inherited"
        return set_operator_context(inherited, inherited_source)
    return set_operator_context(str(uuid.uuid4()), "auto-generated")


def current_operator_identity() -> tuple[str, str]:
    """Return the current operator identity, generating one only if absent."""
    return resolve_operator_identity(None)


def set_author_context(author_id: str, source: str) -> tuple[str, str]:
    """Set the process-wide certificate-author context inherited by child processes."""
    normalized = canonical_uuid(author_id)
    normalized_source = str(source)
    if normalized_source not in _IDENTITY_SOURCES:
        raise ValueError(f"invalid author ID source: {source!r}")
    os.environ[AUTHOR_ID_ENV] = normalized
    os.environ[AUTHOR_ID_SOURCE_ENV] = normalized_source
    return normalized, normalized_source


def resolve_author_identity(
    explicit_author_id: str | None = None,
    *,
    fallback_operator_id: str | None = None,
) -> tuple[str, str]:
    """Resolve a run-scoped certificate-author UUID.

    Resolution order:
      1. explicit command option -> user-specified;
      2. inherited process environment -> inherited/original source;
      3. resolved operator identity -> operator-derived.
    """
    if explicit_author_id:
        return set_author_context(explicit_author_id, "user-specified")
    inherited = os.environ.get(AUTHOR_ID_ENV)
    if inherited:
        inherited_source = os.environ.get(AUTHOR_ID_SOURCE_ENV, "inherited")
        if inherited_source not in _IDENTITY_SOURCES:
            inherited_source = "inherited"
        return set_author_context(inherited, inherited_source)
    operator_id = fallback_operator_id
    if operator_id is None:
        operator_id, _ = current_operator_identity()
    return set_author_context(operator_id, "operator-derived")


def current_author_identity() -> tuple[str, str]:
    """Return the current certificate-author identity."""
    return resolve_author_identity(None)


def canonical_json(obj: object) -> bytes:
    return json.dumps(
        obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False
    ).encode("utf-8")


def digest_object(obj: object) -> str:
    return hashlib.sha256(canonical_json(obj)).hexdigest()


def sha256_file(path: Path) -> str:
    digest = hashlib.sha256()
    with Path(path).open("rb") as stream:
        for block in iter(lambda: stream.read(1 << 20), b""):
            digest.update(block)
    return digest.hexdigest()


def add_creation_metadata(certificate: Dict[str, object], generator_id: str) -> Dict[str, object]:
    """Add immutable author, generator, operator, and creation-time metadata."""
    author_id, _author_source = current_author_identity()
    operator_id, operator_source = current_operator_identity()
    certificate.update(
        {
            "certificate_metadata_schema": CERTIFICATE_METADATA_SCHEMA,
            "certificate_author_id": author_id,
            "certificate_generation_operator_id": operator_id,
            "certificate_generation_operator_id_source": operator_source,
            "certificate_created_at": iso_now(),
            "certificate_generator_program_id": str(generator_id),
            "certificate_verifier_program_id": None,
            "certificate_verification_operator_id": None,
            "certificate_verification_operator_id_source": None,
            "certificate_verified_at": None,
            "certificate_verification_status": "PENDING",
            "verified_payload_sha256": None,
        }
    )
    return certificate


def payload_for_digest(certificate: Dict[str, object], digest_field: str) -> Dict[str, object]:
    """Return the immutable certificate payload used by the certificate digest."""
    payload = dict(certificate)
    payload.pop(digest_field, None)
    for field in _VERIFICATION_FIELDS:
        payload.pop(field, None)
    return payload


def certificate_digest(certificate: Dict[str, object], digest_field: str) -> str:
    return digest_object(payload_for_digest(certificate, digest_field))


def _is_uuid(value: object) -> bool:
    if not isinstance(value, str) or not value:
        return False
    try:
        return canonical_uuid(value) == value.lower()
    except ValueError:
        return False


def metadata_checks(certificate: Dict[str, object], generator_id: str) -> Dict[str, bool]:
    created_at = certificate.get("certificate_created_at")
    operator_source = certificate.get("certificate_generation_operator_id_source")
    return {
        "certificate_metadata_schema_ok": certificate.get("certificate_metadata_schema")
        == CERTIFICATE_METADATA_SCHEMA,
        "certificate_author_id_ok": _is_uuid(
            certificate.get("certificate_author_id")
        ),
        "certificate_generation_operator_id_ok": _is_uuid(
            certificate.get("certificate_generation_operator_id")
        ),
        "certificate_generation_operator_id_source_ok": operator_source
        in _IDENTITY_SOURCES,
        "certificate_created_at_present": isinstance(created_at, str) and bool(created_at),
        "certificate_generator_program_id_ok": certificate.get(
            "certificate_generator_program_id"
        )
        == str(generator_id),
    }


def finalize_certificate(
    certificate_path: Path,
    certificate: Dict[str, object],
    *,
    verifier_program_id: str,
    verification_status: str,
    digest_field: str,
) -> Dict[str, object]:
    """Record the first successful issuance verification in the certificate.

    The issuance verification record is immutable for an unchanged payload. Later
    re-verifications are recorded by their verification summary files and do not
    rewrite the already-issued certificate or invalidate parent hash chains.
    """
    expected_payload_digest = certificate_digest(certificate, digest_field)
    operator_id, operator_source = current_operator_identity()
    preserved = (
        certificate.get("certificate_verifier_program_id") == str(verifier_program_id)
        and certificate.get("certificate_verification_status") == str(verification_status)
        and certificate.get("verified_payload_sha256") == expected_payload_digest
        and _is_uuid(certificate.get("certificate_verification_operator_id"))
        and certificate.get("certificate_verification_operator_id_source") in _IDENTITY_SOURCES
        and isinstance(certificate.get("certificate_verified_at"), str)
        and bool(certificate.get("certificate_verified_at"))
    )
    if not preserved:
        certificate["certificate_verifier_program_id"] = str(verifier_program_id)
        certificate["certificate_verification_operator_id"] = operator_id
        certificate["certificate_verification_operator_id_source"] = operator_source
        certificate["certificate_verified_at"] = iso_now()
        certificate["certificate_verification_status"] = str(verification_status)
        certificate["verified_payload_sha256"] = expected_payload_digest
        Path(certificate_path).write_text(
            json.dumps(certificate, ensure_ascii=False, indent=2) + "\n",
            encoding="utf-8",
        )
    return certificate


def verification_record(certificate: Dict[str, object]) -> Dict[str, object]:
    """Return the immutable issuance metadata stored in the certificate."""
    return {
        "certificate_author_id": certificate.get("certificate_author_id"),
        "certificate_generation_operator_id": certificate.get(
            "certificate_generation_operator_id"
        ),
        "certificate_generation_operator_id_source": certificate.get(
            "certificate_generation_operator_id_source"
        ),
        "certificate_created_at": certificate.get("certificate_created_at"),
        "certificate_generator_program_id": certificate.get(
            "certificate_generator_program_id"
        ),
        "certificate_verifier_program_id": certificate.get(
            "certificate_verifier_program_id"
        ),
        "certificate_verification_operator_id": certificate.get(
            "certificate_verification_operator_id"
        ),
        "certificate_verification_operator_id_source": certificate.get(
            "certificate_verification_operator_id_source"
        ),
        "certificate_verified_at": certificate.get("certificate_verified_at"),
        "certificate_verification_status": certificate.get(
            "certificate_verification_status"
        ),
        "verified_payload_sha256": certificate.get("verified_payload_sha256"),
    }


def verification_execution_record() -> Dict[str, object]:
    """Return the operator identity of the current verification invocation."""
    operator_id, source = current_operator_identity()
    return {
        "verification_execution_operator_id": operator_id,
        "verification_execution_operator_id_source": source,
    }

I.12.8 LIC_complete_cycle_classification.py

#!/usr/bin/env python3
"""Generator for the complete positive-integer periodic-lift classification certificate.

Source metadata:
    File name: LIC_complete_cycle_classification.py
    Program version: X04a
    Source file version: 1.0.2
    Created: 2026-07-29 23:55:10 JST
    Last updated: 2026-08-02 16:32:00 JST

Function summary:
    Combines the all-length structural theorem, cycle-minimum bounds, exhaustive minimum-
    candidate audit, and related evidence into the Layer 1 classification certificate.

Remarks:
    The certificate composes previously generated evidence and records their hashes; it does not
    silently regenerate missing child evidence.
    Individual source-file versioning starts with this metadata revision. Earlier file-level
    changes are retained in package history but are not reconstructed as separate source-file
    versions.

Change history:
    - 1.0.2 / X04a / 2026-08-02 16:32:00 JST
      Updated X04a Program-membership metadata; executable logic is unchanged.
    - 1.0.1 / X03f / 2026-08-01 23:28:33 JST
      Updated the source metadata header for inclusion in the X03f Program package; executable logic is unchanged.
    - 1.0.0 / X03e / 2026-08-01 05:17:15 JST
      Added the standardized English source metadata header and established the
      initial individual source-file version baseline.
"""
from __future__ import annotations

import hashlib
import json
from pathlib import Path
from typing import Dict

from LIC_certificate_metadata import add_creation_metadata, certificate_digest
from LIC_cycle_minimum_audit import AUDIT_ID, write_minimum_candidate_audit
from LIC_cycle_minimum_audit_verifier import verify_run as verify_minimum_audit
from LIC_phase_b_structure import THEOREM_ID, write_certificate as write_window_theorem
from LIC_finite_lp_cycle_bridge import BRIDGE_ID, write_certificate as write_lp_bridge
from LIC_finite_lp_cycle_bridge_verifier import verify_run as verify_lp_bridge
from LIC_phase_b_structure_verifier import verify_run as verify_window_theorem
from LIC_version import PACKAGE_LABEL, PACKAGE_VERSION
from LIC_status import STATUS_FAIL, STATUS_PASS

__program_id__ = "LIC_complete_cycle_classification"
__version__ = PACKAGE_VERSION
CLASSIFICATION_ID = "LIC-COMPLETE-POSITIVE-PERIODIC-LIFT-CLASSIFICATION-v2"


def _sha(path: Path) -> str:
    h = hashlib.sha256()
    with Path(path).open("rb") as f:
        for b in iter(lambda: f.read(1 << 20), b""):
            h.update(b)
    return h.hexdigest()


def _digest(obj: object) -> str:
    return hashlib.sha256(json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")).hexdigest()


def write_complete_classification(M: int, out_dir: Path, block_size: int = 4096) -> Dict[str, object]:
    out_dir = Path(out_dir); out_dir.mkdir(parents=True, exist_ok=True)
    theorem_dir = out_dir / "all_length_objective_window_theorem"
    bridge_dir = out_dir / "finite_lp_cycle_bridge"
    audit_dir = out_dir / "minimum_candidate_audit"
    theorem = write_window_theorem(theorem_dir)
    theorem_verify = verify_window_theorem(theorem_dir)
    bridge = write_lp_bridge(int(M), bridge_dir)
    bridge_verify = verify_lp_bridge(bridge_dir)
    audit = write_minimum_candidate_audit(int(M), audit_dir, block_size=block_size)
    audit_verify = verify_minimum_audit(audit_dir)
    theorem_ok = theorem.get("theorem_id") == THEOREM_ID and theorem_verify.get("verification_status") == "PASS"
    bridge_ok = bridge.get("bridge_id") == BRIDGE_ID and bridge_verify.get("verification_status") == "PASS"
    audit_ok = audit.get("audit_id") == AUDIT_ID and audit_verify.get("verification_status") == "PASS" and int(audit.get("nontrivial_return_count", -1)) == 0
    status = STATUS_PASS if theorem_ok and bridge_ok and audit_ok else STATUS_FAIL
    core: Dict[str, object] = {
        "classification_id": CLASSIFICATION_ID,
        "package_label": PACKAGE_LABEL,
        "M": int(M),
        "maximum_simple_logical_cycle_length": int(audit["maximum_cycle_length"]),
        "global_minimum_value_bound": int(audit["global_minimum_value_bound"]),
        "total_odd_minimum_candidates_audited": int(audit["total_odd_minimum_candidates"]),
        "positive_integer_periodic_lifts_found": int(audit["returned_to_start_count"]),
        "nontrivial_positive_integer_periodic_lifts_found": int(audit["nontrivial_return_count"]),
        "trivial_1_loop_confirmed": audit.get("returned_cycle_summaries") == [{"minimum_candidate": 1, "steps": 1, "sum_T": 2, "max_value_bit_length": 1}],
        "all_length_objective_window_theorem_pass": theorem_ok,
        "finite_lp_cycle_bridge_pass": bridge_ok,
        "complete_minimum_candidate_audit_pass": audit_ok,
        "bridge_to_finite_lp_extreme_cycles": [
            "Every finite circulation extreme ray is supported on a simple directed cycle.",
            "Every simple logical R-cycle has odd-transition length at most the number of odd finite states M/2.",
            "Every positive-integer periodic lift has a minimum odd value satisfying the exact global minimum bound.",
            "The direct R audit exhausts every odd minimum candidate through that bound for at least M/2 odd transitions.",
        ],
        "certificate_scope": "positive-integer periodic lifts of simple logical R-cycle extreme candidates in the exact finite R graph",
        "periodic_lift_classification_certificate_issued": status == STATUS_PASS,
        "appendix_i_combined_certificate_issued": False,
        "unrestricted_positive_cycle_length_claimed": False,
        "underlying_micrograph_edge_deletion_applied": False,
        "critical_window_cycle_enumeration_required": False,
        "finite_check_certificate_issued": status == STATUS_PASS,
        "pass_trivial_only": status == STATUS_PASS,
        "theorem_certificate_sha256": _sha(theorem_dir / "phase_b_structure_certificate.json"),
        "theorem_verify_sha256": _sha(theorem_dir / "phase_b_structure_verify_summary.json"),
        "lp_cycle_bridge_certificate_sha256": _sha(bridge_dir / "finite_lp_cycle_bridge_certificate.json"),
        "lp_cycle_bridge_verify_sha256": _sha(bridge_dir / "finite_lp_cycle_bridge_verify_summary.json"),
        "minimum_audit_summary_sha256": _sha(audit_dir / "cycle_minimum_candidate_audit_summary.json"),
        "minimum_audit_verify_sha256": _sha(audit_dir / "cycle_minimum_candidate_audit_verify_summary.json"),
        "status": status,
    }
    add_creation_metadata(core, __program_id__)
    core["classification_certificate_sha256"] = certificate_digest(core, "classification_certificate_sha256")
    (out_dir / "complete_cycle_classification_certificate.json").write_text(json.dumps(core, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    report = [
        f"# Complete positive-integer periodic-lift classification — M={M}", "",
        f"- package: `{PACKAGE_LABEL}`",
        f"- status: **{status}**",
        f"- maximum simple cycle length: `{core['maximum_simple_logical_cycle_length']}`",
        f"- global minimum candidate bound: `{core['global_minimum_value_bound']}`",
        f"- odd minimum candidates audited: `{core['total_odd_minimum_candidates_audited']}`",
        f"- nontrivial positive-integer periodic lifts: `{core['nontrivial_positive_integer_periodic_lifts_found']}`",
        f"- trivial-only classification: `{str(core['pass_trivial_only']).lower()}`",
        f"- critical-window cycle enumeration required: `{str(core['critical_window_cycle_enumeration_required']).lower()}`",
    ]
    (out_dir / "complete_cycle_classification_report.md").write_text("\n".join(report) + "\n", encoding="utf-8")
    return core


if __name__ == "__main__":
    import argparse
    ap = argparse.ArgumentParser(); ap.add_argument("--M", type=int, required=True); ap.add_argument("--out-dir", required=True); ap.add_argument("--block-size", type=int, default=4096)
    ns = ap.parse_args(); print(json.dumps(write_complete_classification(ns.M, Path(ns.out_dir), ns.block_size), ensure_ascii=False, indent=2))

I.12.9 LIC_complete_cycle_classification_verifier.py

#!/usr/bin/env python3
"""Independent verifier for the complete cycle-classification certificate.

Source metadata:
    File name: LIC_complete_cycle_classification_verifier.py
    Program version: X04a
    Source file version: 1.1.1
    Created: 2026-07-29 23:57:06 JST
    Last updated: 2026-08-02 16:32:00 JST

Function summary:
    Checks Layer 1 metadata, child evidence, candidate coverage, terminal classifications,
    trivial-loop-only result, and certificate digest consistency.

Remarks:
    The verifier is separate from the classification generator and treats any unverified child
    evidence as a failure.
    Individual source-file versioning starts with this metadata revision. Earlier file-level
    changes are retained in package history but are not reconstructed as separate source-file
    versions.

Change history:
    - 1.1.1 / X04a / 2026-08-02 16:32:00 JST
      Updated X04a Program-membership metadata; executable logic is unchanged.
    - 1.1.0 / X03f / 2026-08-01 23:33:00 JST
      Added author-identity consistency verification across the classification certificate and all Layer 1 child certificates.
    - 1.0.1 / X03f / 2026-08-01 23:28:33 JST
      Updated the source metadata header for inclusion in the X03f Program package; executable logic is unchanged.
    - 1.0.0 / X03e / 2026-08-01 05:17:15 JST
      Added the standardized English source metadata header and established the
      initial individual source-file version baseline.
"""
from __future__ import annotations

import hashlib
import json
from pathlib import Path
from typing import Dict

from LIC_certificate_metadata import certificate_digest, finalize_certificate, metadata_checks, verification_record
from LIC_cycle_minimum_audit_verifier import verify_run as verify_minimum_audit
from LIC_phase_b_structure_verifier import verify_run as verify_window_theorem
from LIC_finite_lp_cycle_bridge_verifier import verify_run as verify_lp_bridge
from LIC_version import PACKAGE_LABEL, PACKAGE_VERSION
from LIC_status import STATUS_FAIL, STATUS_PASS

__program_id__ = "LIC_complete_cycle_classification_verifier"
__version__ = PACKAGE_VERSION


def _canonical(obj: object) -> bytes:
    return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")


def _digest(obj: object) -> str:
    return hashlib.sha256(_canonical(obj)).hexdigest()


def _sha(path: Path) -> str:
    h = hashlib.sha256()
    with Path(path).open("rb") as f:
        for b in iter(lambda: f.read(1 << 20), b""):
            h.update(b)
    return h.hexdigest()


def verify_run(run_dir: Path) -> Dict[str, object]:
    run_dir = Path(run_dir)
    cert_path = run_dir / "complete_cycle_classification_certificate.json"
    cert = json.loads(cert_path.read_text(encoding="utf-8"))
    theorem_dir = run_dir / "all_length_objective_window_theorem"
    bridge_dir = run_dir / "finite_lp_cycle_bridge"
    audit_dir = run_dir / "minimum_candidate_audit"
    tv = verify_window_theorem(theorem_dir); bv = verify_lp_bridge(bridge_dir); av = verify_minimum_audit(audit_dir)
    theorem = json.loads((theorem_dir / "phase_b_structure_certificate.json").read_text(encoding="utf-8"))
    bridge = json.loads((bridge_dir / "finite_lp_cycle_bridge_certificate.json").read_text(encoding="utf-8"))
    audit = json.loads((audit_dir / "cycle_minimum_candidate_audit_summary.json").read_text(encoding="utf-8"))
    expected_bridge = [
        "Every finite circulation extreme ray is supported on a simple directed cycle.",
        "Every simple logical R-cycle has odd-transition length at most the number of odd finite states M/2.",
        "Every positive-integer periodic lift has a minimum odd value satisfying the exact global minimum bound.",
        "The direct R audit exhausts every odd minimum candidate through that bound for at least M/2 odd transitions.",
    ]
    checks = {
        **metadata_checks(cert, "LIC_complete_cycle_classification"),
        "package_label_ok": cert.get("package_label") == PACKAGE_LABEL,
        "child_certificate_author_ids_match": (
            cert.get("certificate_author_id")
            == theorem.get("certificate_author_id")
            == bridge.get("certificate_author_id")
            == audit.get("certificate_author_id")
        ),
        "classification_id_ok": cert.get("classification_id") == "LIC-COMPLETE-POSITIVE-PERIODIC-LIFT-CLASSIFICATION-v2",
        "classification_digest_ok": cert.get("classification_certificate_sha256") == certificate_digest(cert, "classification_certificate_sha256"),
        "bridge_content_ok": cert.get("bridge_to_finite_lp_extreme_cycles") == expected_bridge,
        "theorem_pass": tv.get("verification_status") == "PASS" and cert.get("all_length_objective_window_theorem_pass") is True,
        "lp_cycle_bridge_pass": bv.get("verification_status") == "PASS" and cert.get("finite_lp_cycle_bridge_pass") is True,
        "minimum_audit_pass": av.get("verification_status") == "PASS" and cert.get("complete_minimum_candidate_audit_pass") is True,
        "M_ok": int(cert.get("M", -1)) == int(audit.get("M", -2)),
        "length_bound_ok": int(cert.get("maximum_simple_logical_cycle_length", -1)) == int(audit.get("maximum_cycle_length", -2)),
        "minimum_bound_ok": int(cert.get("global_minimum_value_bound", -1)) == int(audit.get("global_minimum_value_bound", -2)),
        "candidate_count_ok": int(cert.get("total_odd_minimum_candidates_audited", -1)) == int(audit.get("total_odd_minimum_candidates", -2)),
        "trivial_only_ok": int(cert.get("positive_integer_periodic_lifts_found", -1)) == int(audit.get("returned_to_start_count", -2)) == 1 and int(cert.get("nontrivial_positive_integer_periodic_lifts_found", -1)) == int(audit.get("nontrivial_return_count", -2)) == 0 and cert.get("trivial_1_loop_confirmed") is True and cert.get("pass_trivial_only") is True,
        "scope_ok": cert.get("certificate_scope") == "positive-integer periodic lifts of simple logical R-cycle extreme candidates in the exact finite R graph" and cert.get("unrestricted_positive_cycle_length_claimed") is False,
        "certificate_gate_ok": cert.get("finite_check_certificate_issued") is True and cert.get("periodic_lift_classification_certificate_issued") is True and cert.get("appendix_i_combined_certificate_issued") is False,
        "no_edge_deletion_ok": cert.get("underlying_micrograph_edge_deletion_applied") is False,
        "no_cycle_enumeration_required_ok": cert.get("critical_window_cycle_enumeration_required") is False,
        "input_hashes_ok": cert.get("theorem_certificate_sha256") == _sha(theorem_dir / "phase_b_structure_certificate.json") and cert.get("theorem_verify_sha256") == _sha(theorem_dir / "phase_b_structure_verify_summary.json") and cert.get("lp_cycle_bridge_certificate_sha256") == _sha(bridge_dir / "finite_lp_cycle_bridge_certificate.json") and cert.get("lp_cycle_bridge_verify_sha256") == _sha(bridge_dir / "finite_lp_cycle_bridge_verify_summary.json") and cert.get("minimum_audit_summary_sha256") == _sha(audit_dir / "cycle_minimum_candidate_audit_summary.json") and cert.get("minimum_audit_verify_sha256") == _sha(audit_dir / "cycle_minimum_candidate_audit_verify_summary.json"),
        "status_ok": cert.get("status") == STATUS_PASS,
    }
    ok = all(checks.values())
    status = STATUS_PASS if ok else STATUS_FAIL
    cert = finalize_certificate(cert_path, cert, verifier_program_id=__program_id__, verification_status=status, digest_field="classification_certificate_sha256")
    result = {
        "package_label": PACKAGE_LABEL, "M": cert.get("M"),
        "verification_status": status,
        "overall_status": STATUS_PASS if ok else STATUS_FAIL,
        "checks": checks,
        **verification_record(cert),
        "verified_certificate_sha256": _sha(cert_path),
    }
    (run_dir / "complete_cycle_classification_verify_summary.json").write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    return result


if __name__ == "__main__":
    import argparse
    ap = argparse.ArgumentParser(); ap.add_argument("run_dir")
    ns = ap.parse_args(); print(json.dumps(verify_run(Path(ns.run_dir)), ensure_ascii=False, indent=2))

I.12.10 LIC_constants.py

#!/usr/bin/env python3
"""Shared constants for the Appendix-I CTV Core package.

Source metadata:
    File name: LIC_constants.py
    Program version: X04a
    Source file version: 1.0.2
    Created: 2026-07-30 01:13:10 JST
    Last updated: 2026-08-02 16:32:00 JST

Function summary:
    Centralizes supported moduli, numeric parameters, schema identifiers, status values,
    filenames, solver names, and display or policy constants used across the Core package.

Remarks:
    Package-wide constants should be added here rather than duplicated as magic literals in
    generators, verifiers, or managers.
    Individual source-file versioning starts with this metadata revision. Earlier file-level
    changes are retained in package history but are not reconstructed as separate source-file
    versions.

Change history:
    - 1.0.2 / X04a / 2026-08-02 16:32:00 JST
      Updated X04a Program-membership metadata; executable logic is unchanged.
    - 1.0.1 / X03f / 2026-08-01 23:28:33 JST
      Updated the source metadata header for inclusion in the X03f Program package; executable logic is unchanged.
    - 1.0.0 / X03e / 2026-08-01 05:17:15 JST
      Added the standardized English source metadata header and established the
      initial individual source-file version baseline.

Detailed description:
    This module collects package-wide numeric parameters, status tokens, solver
    names, schema values, and display constants.  It exists to avoid scattering
    magic numbers and repeated literal policy values across manager, stage,
    verifier, probe, and tool scripts.
"""
from __future__ import annotations

# Audit/output formatting.
AUDIT_SEPARATOR_WIDTH = 72
FILE_HASH_CHUNK_BYTES = 1024 * 1024

# Public finite-check modulus range.
PUBLIC_B_MIN = 10
PUBLIC_B_MAX = 16
STANDARD_SUPPORTED_B_VALUES = tuple(range(PUBLIC_B_MIN, PUBLIC_B_MAX + 1))
STANDARD_SUPPORTED_M_VALUES = tuple(1 << b for b in STANDARD_SUPPORTED_B_VALUES)
STANDARD_SUPPORTED_M_TEXT = ", ".join(str(m) for m in STANDARD_SUPPORTED_M_VALUES)
STANDARD_SUPPORTED_B_RANGE_TEXT = f"{PUBLIC_B_MIN}..{PUBLIC_B_MAX}"

# Adopted/formal certificate defaults.
DEFAULT_FORMAL_B = 12
DEFAULT_LIFT_BITS = 4
DEFAULT_LIFT_BITS_TEXT = str(DEFAULT_LIFT_BITS)
FORMAL_CERTIFICATE_LP_ENGINE = "auto"
FORMAL_CERTIFICATE_LP_ENGINE_POLICY = (
    "formal-finite-check-default: all/generate-only/verify-full use auto; direct HiGHS preferred with SciPy HiGHS fallback"
)

# Public probe/resource defaults.
PUBLIC_DEFAULT_MAX_ITERATIONS = 4000
PUBLIC_DEFAULT_MAX_SEARCH_NODES = 3_000_000_000
STAGE_DEFAULT_MAX_SEARCH_NODES = 10_000_000
STAGE_DEFAULT_MAX_SEARCH_NODES_TEXT = str(STAGE_DEFAULT_MAX_SEARCH_NODES)
DEFAULT_CHECKPOINT_EVERY = 1
DEFAULT_PREPRUNE_CHECKPOINT_EVERY = 10
DEFAULT_PREPRUNE_MAX_PATTERNS = 0
DEFAULT_AUTO_REACH_MAX_EXTRA_ITERATIONS = 100
PREPRUNE_PRIORITY_SENTINEL = 999999
CATALOG_SORT_FALLBACK_PRIORITY = 999999999
PREPRUNE_TOOL_MAX_SEARCH_NODES = 100_000_000

# Numerical tolerances and targets.
TARGET_LAMBDA_DEFAULT = 1.0
TARGET_LAMBDA_DEFAULT_TEXT = "1.0"
LAMBDA_COMPARISON_TOL = 1e-9
AVG_EXTRA_COMPARISON_TOL = 1e-12
LP_PRIMAL_TOL_DEFAULT_TEXT = "1e-9"
LP_DUAL_TOL_DEFAULT_TEXT = "1e-8"
LP_SUPPORT_TOL_DEFAULT_TEXT = "1e-8"
LP_Q_POSITIVE_TOL = 1e-10
NEGATIVE_CYCLE_TOL = 1e-8
SUPPORT_EXTRACTION_TOL = 1e-8
SUPPORT_EXTRACTION_TOL_TEXT = "1e-8"

# X02 exact R-transition development policy.
X02_PRIMARY_B_VALUES = (10, 11, 12)
X02_PRIMARY_M_VALUES = tuple(1 << b for b in X02_PRIMARY_B_VALUES)
R_TRANSITION_MODEL_EXACT_LOGICAL_EDGE = "R_EXACT_LOGICAL_EDGE"
R_TRANSITION_SCHEMA_VERSION = 1

# Collatz arithmetic constants.
COLLATZ_MULTIPLIER = 3
COLLATZ_INCREMENT = 1
DEFAULT_ODD_TRANSITION_DIVISIONS = 1
ODD_RESIDUE_MOD_TWO = 1
EVEN_RESIDUE_MOD_TWO = 0
TRIVIAL_ODD_T_PATTERN = "2"

# LP engine names and command choices.
LP_ENGINE_AUTO = "auto"
LP_ENGINE_SCIPY_ALIAS = "scipy"
LP_ENGINE_SCIPY_HIGHS = "scipy-linprog-highs"
LP_ENGINE_HIGHS_DIRECT = "highs-direct-stateful"
LP_ENGINE_HIGHS_LEGACY_ALIAS = "highspy-stateful"
LP_ENGINE_CHOICES = [
    LP_ENGINE_AUTO,
    LP_ENGINE_SCIPY_ALIAS,
    LP_ENGINE_SCIPY_HIGHS,
    LP_ENGINE_HIGHS_LEGACY_ALIAS,
    LP_ENGINE_HIGHS_DIRECT,
]
LP_ENGINE_ALIASES = {
    LP_ENGINE_SCIPY_ALIAS: LP_ENGINE_SCIPY_HIGHS,
    LP_ENGINE_SCIPY_HIGHS: LP_ENGINE_SCIPY_HIGHS,
    LP_ENGINE_HIGHS_LEGACY_ALIAS: LP_ENGINE_HIGHS_DIRECT,
    LP_ENGINE_HIGHS_DIRECT: LP_ENGINE_HIGHS_DIRECT,
    LP_ENGINE_AUTO: LP_ENGINE_AUTO,
}
HIGHS_DIRECT_BACKEND_CANDIDATES = [
    ("official-highspy", "highspy"),
    ("scipy-embedded-highs-core", "scipy.optimize._highspy._core"),
    ("scipy-embedded-highs-core-legacy", "scipy.optimize._highs._core"),
]

# Closed-walk membership mode.
CLOSED_WALK_ROTATION_MODE_SINGLE = "single"
CLOSED_WALK_ROTATION_MODE_CHOICES = [CLOSED_WALK_ROTATION_MODE_SINGLE]

# Preprune modes.
PREPRUNE_MODE_OFF = "off"
PREPRUNE_MODE_SEEN_M = "seen-M"
PREPRUNE_MODE_ALL = "all"
PREPRUNE_MODE_CHOICES = [PREPRUNE_MODE_OFF, PREPRUNE_MODE_SEEN_M, PREPRUNE_MODE_ALL]

# Schema/status values.
#
# The accepted catalog schema keeps the historical machine-readable
# ``integer_point_filter_result`` values ``forbid`` / ``allow`` for backward
# compatibility with already generated catalog CSV/JSON files.
#
# New human-facing probe logs use the status-form field:
#   integer_point_status=forbidden
#   integer_point_status=allowed
#
# The misspelled legacy display value ``forbiden`` is retained only so old
# log-derived candidate files remain readable.
INTEGER_POINT_FORBID_VALUE = "forbid"
INTEGER_POINT_ALLOW_VALUE = "allow"
INTEGER_POINT_FORBIDDEN_STATUS_VALUE = "forbidden"
INTEGER_POINT_ALLOWED_STATUS_VALUE = "allowed"
INTEGER_POINT_FORBIDEN_LOG_LABEL = "forbiden"  # legacy misspelling, read-only compatibility

# X01f forbidden-scope classification.
#
# ``periodic_closure_status`` states whether the complete t-pattern has a
# positive integer periodic point returning to the same integer.  This is the
# exact property historically exposed as ``integer_point_status``.
#
# ``segment_passage_status`` is a different property: whether the finite
# t-pattern can occur as a positive-integer transition segment without requiring
# the final integer to equal the initial integer.  Every nonempty positive
# t-pattern used by the current LIC graph is allowed by the finite t-pattern
# lift theorem; therefore it is not eligible for substring/extension closure.
PERIODIC_CLOSURE_FORBIDDEN_STATUS_VALUE = "forbidden"
PERIODIC_CLOSURE_ALLOWED_STATUS_VALUE = "allowed"
SEGMENT_PASSAGE_ALLOWED_BY_LIFT_STATUS_VALUE = "allowed_by_finite_t_pattern_lift_theorem"
SEGMENT_PASSAGE_NOT_EVALUATED_INVALID_PATTERN_STATUS_VALUE = "not_evaluated_invalid_t_pattern"
SEGMENT_PASSAGE_BASIS_FINITE_T_PATTERN_LIFT = "finite_positive_t_pattern_lift_theorem"
FORBIDDEN_SCOPE_PERIODIC_CLOSURE_ONLY = "periodic_closure_only"
FORBIDDEN_SCOPE_NOT_FORBIDDEN = "not_forbidden"
STATIC_CHECK_FORBID_VERIFIED = "forbid_verified"
STATIC_CHECK_FORBID_VERIFIED_METADATA_WARNING = "forbid_verified_metadata_warning"
CATALOG_STATUS_ACCEPTED = "accepted"
CATALOG_STATUS_NEEDS_REVIEW = "needs_review"

# Common boolean text accepted by CLI/csv helpers.
TRUE_TEXT_VALUES = {"1", "true", "t", "yes", "y", "on"}
FALSE_TEXT_VALUES = {"0", "false", "f", "no", "n", "off"}
CSV_TRUE_TEXT_VALUES = {"true", "1", "yes", "pass"}

# Miscellaneous safety/display constants.
PATH_PREVIEW_MAX_ITEMS = 20
DEFAULT_B_RANGE_SEPARATOR = ":"
EMPTY_STRING = ""

I.12.11 LIC_independent_ch3_math.py

#!/usr/bin/env python3
"""From-scratch mathematical reconstruction for Chapter 3 verification.

Source metadata:
    File name: LIC_independent_ch3_math.py
    Program version: X04a
    Source file version: 1.0.0
    Created: 2026-08-02 16:32:00 JST
    Last updated: 2026-08-02 16:32:00 JST

Function summary:
    Reconstructs the exact R-micrograph, enumerates derived logical R-edges by an
    implementation-independent path search, recomputes all minimum-value bounds,
    audits all odd minimum candidates, and reconstructs the structural value.

Remarks:
    This module uses only Python's standard library and does not import any generator,
    graph-builder, bound, audit, certificate, or verifier module from the CTV Program.
    Its algorithms are intentionally separate from the production implementation to
    reduce common-mode implementation failures between generation and verification.

Change history:
    - 1.0.0 / X04a / 2026-08-02 16:32:00 JST
      Added the independent Chapter 3 mathematical reconstruction layer.
"""
from __future__ import annotations

from dataclasses import dataclass
import hashlib
import json
from typing import Dict, Iterable, Iterator, List, Mapping, Sequence, Tuple

__program_id__ = "LIC_independent_ch3_math"
__version__ = "X04a"

PHASE_ODD = "ODD_BOUNDARY"
PHASE_AFTER = "AFTER_3N_PLUS_1"
PHASE_DIV = "DIVISION_CONTINUE"
OP_3N1 = "APPLY_3N_PLUS_1"
OP_FIRST_DIV2 = "FIRST_DIVIDE_BY_2"
OP_EXTRA_DIV2 = "EXTRA_DIVIDE_BY_2"

State = Tuple[str, int]
MicroEdgeRow = Tuple[int, State, State, str, int, int]
LogicalEdgeRow = Tuple[int, int, int, int, int, int, Tuple[int, ...]]


def _require_modulus(M: int) -> int:
    if isinstance(M, bool) or not isinstance(M, int) or M < 4 or (M & (M - 1)):
        raise ValueError(f"M must be a power of two >= 4, got {M!r}")
    return M


def canonical_json_bytes(value: object) -> bytes:
    return json.dumps(
        value, sort_keys=True, separators=(",", ":"), ensure_ascii=False
    ).encode("utf-8")


def sha256_payload(value: object) -> str:
    return hashlib.sha256(canonical_json_bytes(value)).hexdigest()


def _state_dict(state: State) -> Dict[str, object]:
    return {"phase": state[0], "residue": state[1]}


def _microedge_dict(edge: MicroEdgeRow) -> Dict[str, object]:
    edge_id, src, dst, operation, odd_count, additional_cost = edge
    return {
        "edge_id": edge_id,
        "src": _state_dict(src),
        "dst": _state_dict(dst),
        "operation": operation,
        "odd_transition_count": odd_count,
        "additional_division_cost": additional_cost,
    }


@dataclass(frozen=True)
class IndependentMicrograph:
    M: int
    states: Tuple[State, ...]
    edges: Tuple[MicroEdgeRow, ...]
    edge_id_by_key: Mapping[Tuple[State, State, str], int]
    outgoing: Mapping[State, Tuple[Tuple[int, State], ...]]

    @property
    def odd_states(self) -> Tuple[State, ...]:
        return tuple(s for s in self.states if s[0] == PHASE_ODD)

    def certificate_payload(self) -> Dict[str, object]:
        return {
            "M": self.M,
            "states": [_state_dict(s) for s in self.states],
            "edges": [_microedge_dict(e) for e in self.edges],
        }

    def certificate_sha256(self) -> str:
        return sha256_payload(self.certificate_payload())


def build_micrograph(M: int) -> IndependentMicrograph:
    """Explicitly construct all states and microedges without CTV graph imports."""
    M = _require_modulus(M)
    odd = tuple(range(1, M, 2))
    even = tuple(range(0, M, 2))
    states: Tuple[State, ...] = tuple(
        [(PHASE_ODD, r) for r in odd]
        + [(PHASE_AFTER, r) for r in even]
        + [(PHASE_DIV, r) for r in even]
    )

    edges: List[MicroEdgeRow] = []
    by_key: Dict[Tuple[State, State, str], int] = {}
    outgoing_lists: Dict[State, List[Tuple[int, State]]] = {s: [] for s in states}
    edge_id = 0

    def add(src: State, dst: State, operation: str, odd_count: int, cost: int) -> None:
        nonlocal edge_id
        key = (src, dst, operation)
        if key in by_key:
            raise AssertionError(f"duplicate independent microedge {key!r}")
        row: MicroEdgeRow = (edge_id, src, dst, operation, odd_count, cost)
        edges.append(row)
        by_key[key] = edge_id
        outgoing_lists[src].append((edge_id, dst))
        edge_id += 1

    for residue in odd:
        add(
            (PHASE_ODD, residue),
            (PHASE_AFTER, (3 * residue + 1) % M),
            OP_3N1,
            1,
            0,
        )

    for phase, operation, cost in (
        (PHASE_AFTER, OP_FIRST_DIV2, 0),
        (PHASE_DIV, OP_EXTRA_DIV2, 1),
    ):
        for residue in even:
            low = residue // 2
            high = low + M // 2
            for quotient in (low, high):
                dst_phase = PHASE_ODD if quotient & 1 else PHASE_DIV
                add((phase, residue), (dst_phase, quotient), operation, 0, cost)

    if len(states) != 3 * M // 2 or len(edges) != 5 * M // 2:
        raise AssertionError("independent micrograph count invariant failed")
    outgoing = {state: tuple(items) for state, items in outgoing_lists.items()}
    return IndependentMicrograph(M, states, tuple(edges), by_key, outgoing)


def micrograph_record(M: int) -> Dict[str, object]:
    graph = build_micrograph(M)
    return {
        "state_count": len(graph.states),
        "microedge_count": len(graph.edges),
        "sha256": graph.certificate_sha256(),
    }


def enumerate_logical_edges(M: int) -> Tuple[LogicalEdgeRow, ...]:
    """Enumerate all simple internal odd-to-odd paths using an independent DFS stack.

    The implementation constructs its own micrograph and does not call the production
    logical-graph builder.  Edge IDs are assigned by the deterministic path discovery
    order required by the certificate canonicalization.
    """
    graph = build_micrograph(M)
    output: List[LogicalEdgeRow] = []
    logical_edge_id = 0

    for residue in range(1, M, 2):
        root: State = (PHASE_ODD, residue)
        after: State = (PHASE_AFTER, (3 * residue + 1) % M)
        first_id = graph.edge_id_by_key[(root, after, OP_3N1)]
        # Explicit stack, independently implemented.  The stored tuple contains
        # current state, ordered microedge path, visited internal states, and t.
        stack: List[Tuple[State, Tuple[int, ...], frozenset[State], int]] = [
            (after, (first_id,), frozenset((root, after)), 0)
        ]
        while stack:
            state, path, visited, division_count = stack.pop()
            for microedge_id, dst in graph.outgoing[state]:
                next_t = division_count + 1
                next_path = path + (microedge_id,)
                if dst[0] == PHASE_ODD:
                    output.append(
                        (
                            logical_edge_id,
                            root[1],
                            dst[1],
                            next_t,
                            next_t - 1,
                            next_t - 2,
                            next_path,
                        )
                    )
                    logical_edge_id += 1
                elif dst not in visited:
                    stack.append((dst, next_path, visited | frozenset((dst,)), next_t))
    return tuple(output)


def logical_graph_record(M: int) -> Dict[str, object]:
    M = _require_modulus(M)
    edges = enumerate_logical_edges(M)
    odd_count = M // 2
    h = hashlib.sha256()
    h.update(f"M={M};odd={odd_count};edges={len(edges)}\n".encode("ascii"))
    for row in edges:
        h.update(canonical_json_bytes(row))
        h.update(b"\n")

    semantic_rows = sorted(
        (src, dst, t, cost, weight, path)
        for _, src, dst, t, cost, weight, path in edges
    )
    semantic_hash = sha256_payload(semantic_rows)
    return {
        "sha256": h.hexdigest(),
        "semantic_sha256": semantic_hash,
        "odd_state_count": odd_count,
        "logical_edge_count": len(edges),
        "edges": edges,
    }


def critical_sum_T_min(length_L: int) -> int:
    L = int(length_L)
    if L <= 0:
        raise ValueError("length_L must be positive")
    return (3 ** L).bit_length()


def minimum_bound_holds(m: int, length_L: int, sum_T: int | None = None) -> bool:
    m = int(m)
    L = int(length_L)
    if m <= 0 or L <= 0:
        return False
    S = critical_sum_T_min(L) if sum_T is None else int(sum_T)
    return (1 << S) * pow(m, L) <= pow(3 * m + 1, L)


def exact_bound_for_length(length_L: int) -> Tuple[int, int]:
    L = int(length_L)
    S = critical_sum_T_min(L)
    low, high = 0, 1
    while minimum_bound_holds(high, L, S):
        low, high = high, high * 2
    while low + 1 < high:
        middle = (low + high) // 2
        if minimum_bound_holds(middle, L, S):
            low = middle
        else:
            high = middle
    return S, low


def compute_bound_rows(max_length: int) -> Tuple[List[Dict[str, object]], int, List[int]]:
    N = int(max_length)
    if N <= 0:
        raise ValueError("max_length must be positive")
    rows: List[Dict[str, object]] = []
    global_bound = 0
    argmax: List[int] = []
    for L in range(1, N + 1):
        S, B = exact_bound_for_length(L)
        rows.append(
            {
                "length_L": L,
                "critical_sum_T_min": S,
                "maximum_minimum_value_B_L": B,
                "bound_holds_at_B_L": minimum_bound_holds(B, L, S),
                "bound_fails_at_B_L_plus_1": not minimum_bound_holds(B + 1, L, S),
            }
        )
        if B > global_bound:
            global_bound, argmax = B, [L]
        elif B == global_bound:
            argmax.append(L)
    return rows, global_bound, argmax


def odd_R_step(n: int) -> Tuple[int, int]:
    value = 3 * int(n) + 1
    t = (value & -value).bit_length() - 1
    return value >> t, t


def audit_one_minimum(m: int, max_length: int) -> Dict[str, object]:
    start = int(m)
    value = start
    maximum = start
    sum_T = 0
    T_pattern: List[int] = []
    for step in range(1, int(max_length) + 1):
        value, t = odd_R_step(value)
        T_pattern.append(t)
        sum_T += t
        maximum = max(maximum, value)
        if value == start:
            reason = "RETURNED_TO_START"
        elif value < start:
            reason = "DESCENDED_BELOW_START"
        else:
            continue
        return {
            "minimum_candidate": start,
            "terminal_reason": reason,
            "steps": step,
            "terminal_value": value,
            "sum_T": sum_T,
            "ordered_T_pattern": tuple(T_pattern),
            "max_value_bit_length": maximum.bit_length(),
        }
    return {
        "minimum_candidate": start,
        "terminal_reason": "NO_RETURN_WITHIN_MAX_LENGTH",
        "steps": int(max_length),
        "terminal_value": value,
        "sum_T": sum_T,
        "ordered_T_pattern": tuple(T_pattern),
        "max_value_bit_length": maximum.bit_length(),
    }


def iter_minimum_audit(global_bound: int, max_length: int) -> Iterator[Dict[str, object]]:
    for minimum in range(1, int(global_bound) + 1, 2):
        yield audit_one_minimum(minimum, max_length)


def reconstruct_structural_values(returned_cycles: Sequence[Mapping[str, object]]) -> List[str]:
    values: List[str] = []
    for cycle in returned_cycles:
        steps = int(cycle["steps"])
        sum_T = int(cycle["sum_T"])
        if steps <= 0:
            raise ValueError("returned cycle length must be positive")
        numerator = sum_T - steps
        if numerator % steps == 0:
            values.append(str(numerator // steps))
        else:
            from fractions import Fraction
            values.append(str(Fraction(numerator, steps)))
    return sorted(set(values))

PHASE_B_THEOREM_ID = "LIC-POSITIVE-CYCLE-OBJECTIVE-WINDOW-v2"


def phase_b_theorem_specification() -> Dict[str, object]:
    """Return the verifier-owned theorem content without generator imports."""
    proof_steps = [
        {"step": 1, "statement": "For each odd transition, 2^T_i * V_(i+1) = 3*V_i + 1."},
        {"step": 2, "statement": "Multiplying around a periodic orbit and cancelling product(V_i) gives 2^S = product_i(3 + 1/V_i)."},
        {"step": 3, "statement": "V_i >= 1 implies 3 < 3 + 1/V_i <= 4, hence 3^L < 2^S <= 4^L."},
        {"step": 4, "statement": "lambda_x = (S-L)/L, hence log_2(3/2) < lambda_x <= 1."},
        {"step": 5, "statement": "Equality S=2L requires every factor 3+1/V_i=4, so every V_i=1 and every T_i=2."},
    ]
    return {
        "theorem_id": PHASE_B_THEOREM_ID,
        "scope": "all positive-integer odd Collatz periodic orbits; all lengths; all powers-of-two M",
        "assumptions": [
            "L is a positive integer",
            "V_i are positive odd integers with cyclic indexing",
            "T_i are positive integers satisfying 2^T_i V_(i+1)=3V_i+1",
        ],
        "proof_steps": proof_steps,
        "conclusions": {
            "below_or_equal_alpha_star": "periodic_closure_forbidden",
            "critical_open_window": "log2(3/2) < lambda_x < 1",
            "phase_B_above_unit": "periodic_closure_forbidden",
            "phase_B_unit": "trivial_1_loop_only",
            "all_length_lower_and_phase_B_complete": True,
            "all_length_phase_B_complete": True,
            "underlying_graph_edge_deletion_required": False,
            "individual_phase_B_family_enumeration_required": False,
        },
        "proof_sha256": sha256_payload(proof_steps),
    }

I.12.12 LIC_core_manager.py

#!/usr/bin/env python3
"""Command manager for the formal Appendix-I finite-check workflow.

Source metadata:
    File name: LIC_core_manager.py
    Program version: X04a
    Source file version: 1.1.1
    Created: 2026-07-29 23:55:10 JST
    Last updated: 2026-08-02 16:32:00 JST

Function summary:
    Provides command-line subcommands that generate and independently verify the complete cycle-
    classification certificate and the two-layer Appendix-I core certificate.

Remarks:
    This manager exposes the formal certificate workflow only. The public one-command interface
    is ctv0100.py.
    Individual source-file versioning starts with this metadata revision. Earlier file-level
    changes are retained in package history but are not reconstructed as separate source-file
    versions.

Change history:
    - 1.1.1 / X04a / 2026-08-02 16:32:00 JST
      Updated X04a Program-membership metadata; executable logic is unchanged.
    - 1.1.0 / X03f / 2026-08-01 23:28:33 JST
      Added --author-id to certificate workflow commands and established independent author and operator identity contexts.
    - 1.0.0 / X03e / 2026-08-01 05:17:15 JST
      Added the standardized English source metadata header and established the
      initial individual source-file version baseline.

Detailed description:
    This manager exposes only the commands required to generate and independently
    verify the current formal certificates.
"""
from __future__ import annotations

import argparse
import json
import shutil
from pathlib import Path

from LIC_constants import STANDARD_SUPPORTED_M_VALUES
from LIC_certificate_metadata import (
    canonical_uuid,
    resolve_author_identity,
    resolve_operator_identity,
)
from LIC_complete_cycle_classification import write_complete_classification
from LIC_complete_cycle_classification_verifier import verify_run as verify_complete_cycle_classification_run
from LIC_appendix_i_core_certificate import write_core_certificate
from LIC_appendix_i_core_certificate_verifier import verify_run as verify_core_certificate_run
from LIC_version import PACKAGE_LABEL
from LIC_status import STATUS_PASS


def _validate_primary_M(M: int, allow_auxiliary: bool) -> None:
    if M in STANDARD_SUPPORTED_M_VALUES:
        return
    if allow_auxiliary and M >= 4 and (M & (M - 1)) == 0:
        return
    raise SystemExit(
        f"M={M} is outside the standard supported range {STANDARD_SUPPORTED_M_VALUES}; "
        "use --allow-auxiliary-M only for an explicitly supplementary run"
    )


def _prepare_output(out_dir: Path, fresh: bool) -> None:
    if out_dir.exists() and fresh:
        shutil.rmtree(out_dir)


def run_complete_cycle_classification(
    M: int, out_dir: Path, fresh: bool, allow_auxiliary: bool, block_size: int
) -> int:
    _validate_primary_M(M, allow_auxiliary)
    _prepare_output(out_dir, fresh)
    result = write_complete_classification(M, out_dir, block_size=block_size)
    print(json.dumps(result, ensure_ascii=False, indent=2))
    return 0 if result.get("status") == STATUS_PASS else 1


def run_verify_complete_cycle_classification(run_dir: Path) -> int:
    result = verify_complete_cycle_classification_run(run_dir)
    print(json.dumps(result, ensure_ascii=False, indent=2))
    return 0 if result.get("verification_status") == "PASS" else 1


def run_appendix_i_core_certificate(
    M: int, out_dir: Path, fresh: bool, allow_auxiliary: bool, block_size: int
) -> int:
    _validate_primary_M(M, allow_auxiliary)
    _prepare_output(out_dir, fresh)
    result = write_core_certificate(M, out_dir, block_size=block_size)
    print(json.dumps(result, ensure_ascii=False, indent=2))
    return 0 if result.get("status") == STATUS_PASS else 1


def run_verify_appendix_i_core_certificate(run_dir: Path, M: int | None = None) -> int:
    result = verify_core_certificate_run(run_dir, M=M)
    print(json.dumps(result, ensure_ascii=False, indent=2))
    return 0 if result.get("verification_status") == "PASS" else 1


def _add_identity_options(parser: argparse.ArgumentParser) -> None:
    parser.add_argument(
        "--author-id",
        type=canonical_uuid,
        help=(
            "optional certificate-author UUID/GUID; when omitted, the resolved "
            "operator UUID is used as the author UUID"
        ),
    )
    parser.add_argument(
        "--operator-id",
        type=canonical_uuid,
        help=(
            "optional operator UUID/GUID for this command invocation; when omitted, "
            "a one-time UUID v4 is generated"
        ),
    )


def build_parser() -> argparse.ArgumentParser:
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument("--version", action="version", version=PACKAGE_LABEL)
    sub = p.add_subparsers(dest="command", required=True)

    cca = sub.add_parser(
        "complete-cycle-classification",
        help="issue the complete positive-integer periodic-lift classification certificate",
    )
    cca.add_argument("--M", type=int, required=True)
    cca.add_argument("--out-dir", type=Path, required=True)
    cca.add_argument("--fresh", action="store_true")
    cca.add_argument("--allow-auxiliary-M", action="store_true")
    cca.add_argument("--block-size", type=int, default=4096)
    _add_identity_options(cca)

    ccav = sub.add_parser(
        "verify-complete-cycle-classification",
        help="independently verify the complete periodic-lift classification certificate",
    )
    ccav.add_argument("--run-dir", type=Path, required=True)
    _add_identity_options(ccav)

    aic = sub.add_parser(
        "appendix-i-core-certificate",
        help="issue the two-layer Appendix-I finite-check certificate for the selected M",
    )
    aic.add_argument("--M", type=int, default=4096)
    aic.add_argument("--out-dir", type=Path, required=True)
    aic.add_argument("--fresh", action="store_true")
    aic.add_argument("--allow-auxiliary-M", action="store_true")
    aic.add_argument("--block-size", type=int, default=4096)
    _add_identity_options(aic)

    aicv = sub.add_parser(
        "verify-appendix-i-core-certificate",
        help="independently verify the selected-M two-layer Appendix-I certificate",
    )
    aicv.add_argument("--run-dir", type=Path, required=True)
    aicv.add_argument("--M", type=int)
    _add_identity_options(aicv)
    return p


def main() -> int:
    a = build_parser().parse_args()
    operator_id, _operator_source = resolve_operator_identity(
        getattr(a, "operator_id", None)
    )
    resolve_author_identity(
        getattr(a, "author_id", None), fallback_operator_id=operator_id
    )
    if a.command == "complete-cycle-classification":
        return run_complete_cycle_classification(
            a.M, a.out_dir, a.fresh, a.allow_auxiliary_M, a.block_size
        )
    if a.command == "verify-complete-cycle-classification":
        return run_verify_complete_cycle_classification(a.run_dir)
    if a.command == "appendix-i-core-certificate":
        return run_appendix_i_core_certificate(
            a.M, a.out_dir, a.fresh, a.allow_auxiliary_M, a.block_size
        )
    if a.command == "verify-appendix-i-core-certificate":
        return run_verify_appendix_i_core_certificate(a.run_dir, a.M)
    raise SystemExit(f"unsupported core command: {a.command}")


if __name__ == "__main__":
    raise SystemExit(main())

I.12.13 LIC_cycle_minimum_audit.py

#!/usr/bin/env python3
"""Exhaustive direct audit of every possible positive cycle minimum.

Source metadata:
    File name: LIC_cycle_minimum_audit.py
    Program version: X04a
    Source file version: 1.0.2
    Created: 2026-07-29 23:55:10 JST
    Last updated: 2026-08-02 16:32:00 JST

Function summary:
    Enumerates every positive odd minimum candidate up to the proven global bound, applies exact
    odd-to-odd Collatz transitions, classifies each candidate, and writes audit evidence.

Remarks:
    All orbit arithmetic is exact integer arithmetic. Candidate coverage is part of the
    generated evidence and is independently verified.
    Individual source-file versioning starts with this metadata revision. Earlier file-level
    changes are retained in package history but are not reconstructed as separate source-file
    versions.

Change history:
    - 1.0.2 / X04a / 2026-08-02 16:32:00 JST
      Updated X04a Program-membership metadata; executable logic is unchanged.
    - 1.0.1 / X03f / 2026-08-01 23:28:33 JST
      Updated the source metadata header for inclusion in the X03f Program package; executable logic is unchanged.
    - 1.0.0 / X03e / 2026-08-01 05:17:15 JST
      Added the standardized English source metadata header and established the
      initial individual source-file version baseline.
"""
from __future__ import annotations

import csv
import hashlib
import json
from collections import Counter
from pathlib import Path
from typing import Dict, List, Tuple

from LIC_certificate_metadata import add_creation_metadata, certificate_digest
from LIC_cycle_minimum_bound import (
    THEOREM_ID, logical_graph_sha256, sha256_file, sha256_payload,
    write_minimum_bound_certificate,
)
from LIC_version import PACKAGE_LABEL, PACKAGE_VERSION
from LIC_status import STATUS_FAIL, STATUS_PASS

__program_id__ = "LIC_cycle_minimum_audit"
__version__ = PACKAGE_VERSION
AUDIT_ID = "LIC-POSITIVE-CYCLE-MINIMUM-CANDIDATE-AUDIT-v2"
GENESIS_HASH = "0" * 64


def _canonical_json(obj: object) -> bytes:
    return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")


def _chain(previous: str, payload: object) -> str:
    h = hashlib.sha256(); h.update(previous.encode("ascii")); h.update(b"\n"); h.update(_canonical_json(payload)); return h.hexdigest()


def odd_collatz_step(n: int) -> Tuple[int, int]:
    x = 3 * int(n) + 1
    lowbit = x & -x
    t = lowbit.bit_length() - 1
    return x >> t, t


def audit_one_minimum(m: int, max_length: int) -> Dict[str, object]:
    start = int(m); n = start; max_value = start; sum_t = 0
    for step in range(1, int(max_length) + 1):
        n, t = odd_collatz_step(n); sum_t += t; max_value = max(max_value, n)
        if n == start:
            return {
                "minimum_candidate": start, "terminal_reason": "RETURNED_TO_START",
                "steps": step, "terminal_value": n, "sum_T": sum_t,
                "max_value_bit_length": max_value.bit_length(),
            }
        if n < start:
            return {
                "minimum_candidate": start, "terminal_reason": "DESCENDED_BELOW_START",
                "steps": step, "terminal_value": n, "sum_T": sum_t,
                "max_value_bit_length": max_value.bit_length(),
            }
    return {
        "minimum_candidate": start, "terminal_reason": "NO_RETURN_WITHIN_MAX_LENGTH",
        "steps": int(max_length), "terminal_value": n, "sum_T": sum_t,
        "max_value_bit_length": max_value.bit_length(),
    }


def write_minimum_candidate_audit(M: int, out_dir: Path, block_size: int = 4096) -> Dict[str, object]:
    M = int(M); out_dir = Path(out_dir); out_dir.mkdir(parents=True, exist_ok=True)
    bound_dir = out_dir / "minimum_bound"
    bound = write_minimum_bound_certificate(M, bound_dir)
    N = int(bound["maximum_cycle_length"]); B = int(bound["global_minimum_value_bound"])
    graph_hash, odd_count, edge_count = logical_graph_sha256(M)
    if graph_hash != bound["logical_graph_sha256"] or odd_count != N:
        raise AssertionError("bound certificate graph mismatch")

    previous = GENESIS_HASH; blocks: List[Dict[str, object]] = []; totals = Counter(); returns: List[Dict[str, object]] = []
    block: List[Dict[str, object]] = []; block_pre = previous; block_index = 0; global_max_steps = 0; global_max_bits = 0

    def flush() -> None:
        nonlocal block, block_pre, block_index
        if not block: return
        c = Counter(x["terminal_reason"] for x in block)
        blocks.append({
            "block_index": block_index,
            "candidate_index_start": totals["candidates"] - len(block),
            "candidate_index_stop": totals["candidates"],
            "minimum_value_start": block[0]["minimum_candidate"],
            "minimum_value_stop": block[-1]["minimum_candidate"],
            "candidate_count": len(block),
            "returned_to_start_count": c["RETURNED_TO_START"],
            "descended_below_start_count": c["DESCENDED_BELOW_START"],
            "no_return_within_max_length_count": c["NO_RETURN_WITHIN_MAX_LENGTH"],
            "block_max_steps": max(int(x["steps"]) for x in block),
            "block_max_value_bit_length": max(int(x["max_value_bit_length"]) for x in block),
            "pre_block_evidence_sha256": block_pre,
            "final_block_evidence_sha256": previous,
        })
        block_index += 1; block = []; block_pre = previous

    candidate_index = 0
    for m in range(1, B + 1, 2):
        payload = audit_one_minimum(m, N)
        payload.update({"M": M, "maximum_cycle_length": N, "candidate_index": candidate_index})
        previous = _chain(previous, payload)
        block.append(payload); candidate_index += 1; totals["candidates"] += 1
        reason = str(payload["terminal_reason"]); totals[reason] += 1
        global_max_steps = max(global_max_steps, int(payload["steps"])); global_max_bits = max(global_max_bits, int(payload["max_value_bit_length"]))
        if reason == "RETURNED_TO_START":
            returns.append({k: payload[k] for k in ("minimum_candidate", "steps", "sum_T", "max_value_bit_length")})
            if not (m == 1 and int(payload["steps"]) == 1 and int(payload["sum_T"]) == 2):
                totals["nontrivial_returns"] += 1
        if len(block) >= int(block_size): flush()
    flush()

    block_csv = out_dir / "cycle_minimum_candidate_audit_blocks.csv"
    with block_csv.open("w", encoding="utf-8", newline="") as f:
        w = csv.DictWriter(f, fieldnames=list(blocks[0])); w.writeheader(); w.writerows(blocks)
    bound_cert = bound_dir / "cycle_minimum_bound_certificate.json"
    bound_csv = bound_dir / "cycle_minimum_bound_lengths.csv"
    status = STATUS_PASS if totals["nontrivial_returns"] == 0 else STATUS_FAIL
    summary: Dict[str, object] = {
        "audit_id": AUDIT_ID,
        "theorem_id": THEOREM_ID,
        "package_label": PACKAGE_LABEL,
        "M": M,
        "maximum_cycle_length": N,
        "odd_state_count": odd_count,
        "logical_edge_count": edge_count,
        "logical_graph_sha256": graph_hash,
        "global_minimum_value_bound": B,
        "total_odd_minimum_candidates": totals["candidates"],
        "returned_to_start_count": totals["RETURNED_TO_START"],
        "descended_below_start_count": totals["DESCENDED_BELOW_START"],
        "no_return_within_max_length_count": totals["NO_RETURN_WITHIN_MAX_LENGTH"],
        "nontrivial_return_count": totals["nontrivial_returns"],
        "returned_cycle_summaries": returns,
        "global_max_steps_before_terminal": global_max_steps,
        "global_max_value_bit_length": global_max_bits,
        "block_size_candidates": int(block_size),
        "block_count": len(blocks),
        "final_candidate_evidence_sha256": previous,
        "blocks_csv_sha256": sha256_file(block_csv),
        "minimum_bound_certificate_sha256": sha256_file(bound_cert),
        "minimum_bound_lengths_csv_sha256": sha256_file(bound_csv),
        "proof_bridge": {
            "simple_cycle_length_bound": "L <= odd_state_count = M/2",
            "minimum_value_bound": "m <= global_minimum_value_bound",
            "exhaustion": "every odd m in [1,B] is iterated under exact R for at least the maximum simple cycle length",
            "cycle_detection": "a cycle whose minimum is m must return to m within its length",
        },
        "certificate_scope": "positive-integer periodic lifts of simple logical R-cycle extreme candidates in the exact finite R graph",
        "periodic_lift_classification_subcertificate_issued": status == STATUS_PASS,
        "appendix_i_combined_certificate_issued": False,
        "unrestricted_positive_cycle_length_claimed": False,
        "underlying_micrograph_edge_deletion_applied": False,
        "finite_check_certificate_issued": status == STATUS_PASS,
        "status": status,
    }
    add_creation_metadata(summary, __program_id__)
    summary["audit_certificate_sha256"] = certificate_digest(summary, "audit_certificate_sha256")
    summary_path = out_dir / "cycle_minimum_candidate_audit_summary.json"
    summary_path.write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    report = [
        f"# Complete positive-cycle minimum-candidate audit — M={M}", "",
        f"- package: `{PACKAGE_LABEL}`",
        f"- status: **{status}**",
        f"- maximum simple cycle length: `{N}`",
        f"- global minimum candidate bound: `{B}`",
        f"- odd candidates audited: `{totals['candidates']}`",
        f"- returned to start: `{totals['RETURNED_TO_START']}`",
        f"- nontrivial returns: `{totals['nontrivial_returns']}`",
        f"- maximum observed terminal step: `{global_max_steps}`",
        f"- final evidence SHA-256: `{previous}`",
    ]
    (out_dir / "cycle_minimum_candidate_audit_report.md").write_text("\n".join(report) + "\n", encoding="utf-8")
    return summary


if __name__ == "__main__":
    import argparse
    ap = argparse.ArgumentParser(); ap.add_argument("--M", type=int, required=True); ap.add_argument("--out-dir", required=True); ap.add_argument("--block-size", type=int, default=4096)
    ns = ap.parse_args(); print(json.dumps(write_minimum_candidate_audit(ns.M, Path(ns.out_dir), ns.block_size), ensure_ascii=False, indent=2))

I.12.14 LIC_cycle_minimum_audit_verifier.py

#!/usr/bin/env python3
"""Independent verifier for minimum bounds and the direct minimum-candidate audit.

Source metadata:
    File name: LIC_cycle_minimum_audit_verifier.py
    Program version: X04a
    Source file version: 2.0.0
    Created: 2026-07-29 23:57:06 JST
    Last updated: 2026-08-02 16:32:00 JST

Function summary:
    Recomputes graph identities, exact length bounds, candidate ranges, sampled or complete
    audit facts, terminal classifications, and evidence digests.

Remarks:
    The verifier independently implements the relevant arithmetic and does not trust generator
    status fields without recomputation.
    Individual source-file versioning starts with this metadata revision. Earlier file-level
    changes are retained in package history but are not reconstructed as separate source-file
    versions.

Change history:
    - 2.0.0 / X04a / 2026-08-02 16:32:00 JST
      Reimplemented graph binding, exact bound validation, and full candidate auditing through the independent Chapter 3 mathematical reconstruction layer.
    - 1.1.0 / X03f / 2026-08-01 23:33:00 JST
      Added author-identity consistency verification between the minimum-bound and minimum-audit certificates.
    - 1.0.1 / X03f / 2026-08-01 23:28:33 JST
      Updated the source metadata header for inclusion in the X03f Program package; executable logic is unchanged.
    - 1.0.0 / X03e / 2026-08-01 05:17:15 JST
      Added the standardized English source metadata header and established the
      initial individual source-file version baseline.
"""
from __future__ import annotations

import csv
import hashlib
import json
from collections import Counter
from pathlib import Path
from typing import Dict, List, Tuple

from LIC_certificate_metadata import certificate_digest, finalize_certificate, metadata_checks, verification_record
from LIC_version import PACKAGE_LABEL, PACKAGE_VERSION
from LIC_status import STATUS_FAIL, STATUS_PASS
from LIC_independent_ch3_math import (
    audit_one_minimum,
    logical_graph_record,
    minimum_bound_holds,
)

__program_id__ = "LIC_cycle_minimum_audit_verifier"
__version__ = PACKAGE_VERSION
GENESIS_HASH = "0" * 64


def _canonical_json(obj: object) -> bytes:
    return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")


def _chain(previous: str, payload: object) -> str:
    h = hashlib.sha256(); h.update(previous.encode("ascii")); h.update(b"\n"); h.update(_canonical_json(payload)); return h.hexdigest()


def _payload_digest(obj: object) -> str:
    return hashlib.sha256(_canonical_json(obj)).hexdigest()


def _sha_file(path: Path) -> str:
    h = hashlib.sha256()
    with Path(path).open("rb") as f:
        for chunk in iter(lambda: f.read(1 << 20), b""):
            h.update(chunk)
    return h.hexdigest()



def verify_run(run_dir: Path) -> Dict[str, object]:
    run_dir = Path(run_dir)
    summary_path = run_dir / "cycle_minimum_candidate_audit_summary.json"
    blocks_path = run_dir / "cycle_minimum_candidate_audit_blocks.csv"
    bound_dir = run_dir / "minimum_bound"
    bound_cert_path = bound_dir / "cycle_minimum_bound_certificate.json"
    bound_csv_path = bound_dir / "cycle_minimum_bound_lengths.csv"
    saved = json.loads(summary_path.read_text(encoding="utf-8"))
    bound = json.loads(bound_cert_path.read_text(encoding="utf-8"))
    M = int(saved["M"])
    independent_graph = logical_graph_record(M)
    graph_hash = str(independent_graph["sha256"])
    graph_semantic_hash = str(independent_graph["semantic_sha256"])
    odd_count = int(independent_graph["odd_state_count"])
    edge_count = int(independent_graph["logical_edge_count"])
    N = odd_count

    rows = list(csv.DictReader(bound_csv_path.open(encoding="utf-8")))
    bound_rows_ok = len(rows) == N
    global_B = 0; argmax: List[int] = []
    if bound_rows_ok:
        for expected_L, row in enumerate(rows, 1):
            L = int(row["length_L"]); S = int(row["critical_sum_T_min"]); B = int(row["maximum_minimum_value_B_L"])
            expected_S = (3 ** L).bit_length()
            ok = (
                L == expected_L and S == expected_S and
                minimum_bound_holds(B, L, S) and not minimum_bound_holds(B + 1, L, S) and
                row["bound_holds_at_B_L"].lower() == "true" and
                row["bound_fails_at_B_L_plus_1"].lower() == "true"
            )
            if not ok:
                bound_rows_ok = False; break
            if B > global_B: global_B = B; argmax = [L]
            elif B == global_B: argmax.append(L)

    saved_blocks = list(csv.DictReader(blocks_path.open(encoding="utf-8")))
    block_size = int(saved["block_size_candidates"]); rebuilt_blocks: List[Dict[str, object]] = []
    previous = GENESIS_HASH; block_payloads: List[Dict[str, object]] = []; block_pre = previous; block_index = 0
    totals = Counter(); returns: List[Dict[str, object]] = []; max_steps = 0; max_bits = 0

    def flush() -> None:
        nonlocal block_payloads, block_pre, block_index
        if not block_payloads: return
        c = Counter(str(x["terminal_reason"]) for x in block_payloads)
        rebuilt_blocks.append({
            "block_index": str(block_index),
            "candidate_index_start": str(totals["candidates"] - len(block_payloads)),
            "candidate_index_stop": str(totals["candidates"]),
            "minimum_value_start": str(block_payloads[0]["minimum_candidate"]),
            "minimum_value_stop": str(block_payloads[-1]["minimum_candidate"]),
            "candidate_count": str(len(block_payloads)),
            "returned_to_start_count": str(c["RETURNED_TO_START"]),
            "descended_below_start_count": str(c["DESCENDED_BELOW_START"]),
            "no_return_within_max_length_count": str(c["NO_RETURN_WITHIN_MAX_LENGTH"]),
            "block_max_steps": str(max(int(x["steps"]) for x in block_payloads)),
            "block_max_value_bit_length": str(max(int(x["max_value_bit_length"]) for x in block_payloads)),
            "pre_block_evidence_sha256": block_pre,
            "final_block_evidence_sha256": previous,
        })
        block_index += 1; block_payloads = []; block_pre = previous

    candidate_index = 0
    for m in range(1, global_B + 1, 2):
        independent = audit_one_minimum(m, N)
        p = {k: independent[k] for k in (
            "minimum_candidate", "terminal_reason", "steps", "terminal_value",
            "sum_T", "max_value_bit_length"
        )}
        p.update({"M": M, "maximum_cycle_length": N, "candidate_index": candidate_index})
        previous = _chain(previous, p); block_payloads.append(p); candidate_index += 1; totals["candidates"] += 1
        reason = str(p["terminal_reason"]); totals[reason] += 1; max_steps = max(max_steps, int(p["steps"])); max_bits = max(max_bits, int(p["max_value_bit_length"]))
        if reason == "RETURNED_TO_START":
            returns.append({k: p[k] for k in ("minimum_candidate", "steps", "sum_T", "max_value_bit_length")})
            if not (m == 1 and int(p["steps"]) == 1 and int(p["sum_T"]) == 2): totals["nontrivial_returns"] += 1
        if len(block_payloads) >= block_size: flush()
    flush()

    expected_proof_steps = [
        "For every positive odd cycle, multiplication of 2^T_i V_(i+1)=3V_i+1 gives 2^S=product_i(3+1/V_i).",
        "With m=min_i V_i, every V_i>=m, hence 2^S<= (3+1/m)^L.",
        "The strict lower product bound gives 3^L<2^S, so S>=bit_length(3^L).",
        "Therefore 2^s_min*m^L <= (3m+1)^L is necessary.",
        "The function 3+1/m is strictly decreasing for positive m; the maximal integer satisfying the inequality is B_L.",
        "A simple logical R-cycle uses distinct odd states, so its length is at most the finite graph odd-state count N=M/2.",
        "Thus the minimum of every positive-integer periodic lift of an LP extreme cycle is at most max_(1<=L<=N) B_L.",
    ]
    expected_bridge = {
        "simple_cycle_length_bound": "L <= odd_state_count = M/2",
        "minimum_value_bound": "m <= global_minimum_value_bound",
        "exhaustion": "every odd m in [1,B] is iterated under exact R for at least the maximum simple cycle length",
        "cycle_detection": "a cycle whose minimum is m must return to m within its length",
    }
    checks = {
        **metadata_checks(saved, "LIC_cycle_minimum_audit"),
        **{f"bound_{k}": v for k, v in metadata_checks(bound, "LIC_cycle_minimum_bound").items()},
        "package_label_ok": saved.get("package_label") == PACKAGE_LABEL and bound.get("package_label") == PACKAGE_LABEL,
        "bound_certificate_author_matches_audit": (
            bound.get("certificate_author_id") == saved.get("certificate_author_id")
        ),
        "ids_ok": saved.get("audit_id") == "LIC-POSITIVE-CYCLE-MINIMUM-CANDIDATE-AUDIT-v2" and saved.get("theorem_id") == "LIC-POSITIVE-CYCLE-MINIMUM-BOUND-v2" and bound.get("theorem_id") == "LIC-POSITIVE-CYCLE-MINIMUM-BOUND-v2",
        "bound_proof_content_ok": bound.get("proof_steps") == expected_proof_steps and bound.get("proof_sha256") == _payload_digest(expected_proof_steps),
        "bound_certificate_digest_ok": bound.get("certificate_sha256") == certificate_digest(bound, "certificate_sha256"),
        "audit_certificate_digest_ok": saved.get("audit_certificate_sha256") == certificate_digest(saved, "audit_certificate_sha256"),
        "proof_bridge_ok": saved.get("proof_bridge") == expected_bridge,
        "graph_binding_ok": saved.get("logical_graph_sha256") == graph_hash == bound.get("logical_graph_sha256") and int(saved.get("odd_state_count", -1)) == odd_count and int(saved.get("logical_edge_count", -1)) == edge_count,
        "maximum_cycle_length_ok": int(saved.get("maximum_cycle_length", -1)) == N == int(bound.get("maximum_cycle_length", -2)),
        "bound_rows_exact_and_maximal": bound_rows_ok,
        "global_bound_ok": global_B == int(saved.get("global_minimum_value_bound", -1)) == int(bound.get("global_minimum_value_bound", -2)),
        "global_bound_argmax_ok": argmax == list(bound.get("global_bound_attained_at_lengths", [])),
        "bound_files_hash_ok": saved.get("minimum_bound_certificate_sha256") == _sha_file(bound_cert_path) and saved.get("minimum_bound_lengths_csv_sha256") == _sha_file(bound_csv_path) and bound.get("lengths_csv_sha256") == _sha_file(bound_csv_path),
        "blocks_exact_match": saved_blocks == rebuilt_blocks,
        "blocks_hash_ok": saved.get("blocks_csv_sha256") == _sha_file(blocks_path),
        "candidate_total_ok": int(saved.get("total_odd_minimum_candidates", -1)) == totals["candidates"] == (global_B + 1) // 2,
        "terminal_counts_ok": int(saved.get("returned_to_start_count", -1)) == totals["RETURNED_TO_START"] and int(saved.get("descended_below_start_count", -1)) == totals["DESCENDED_BELOW_START"] and int(saved.get("no_return_within_max_length_count", -1)) == totals["NO_RETURN_WITHIN_MAX_LENGTH"],
        "nontrivial_return_zero": int(saved.get("nontrivial_return_count", -1)) == totals["nontrivial_returns"] == 0,
        "returned_cycles_ok": saved.get("returned_cycle_summaries") == returns == [{"minimum_candidate": 1, "steps": 1, "sum_T": 2, "max_value_bit_length": 1}],
        "maxima_ok": int(saved.get("global_max_steps_before_terminal", -1)) == max_steps and int(saved.get("global_max_value_bit_length", -1)) == max_bits,
        "final_evidence_hash_ok": saved.get("final_candidate_evidence_sha256") == previous,
        "scope_ok": saved.get("certificate_scope") == "positive-integer periodic lifts of simple logical R-cycle extreme candidates in the exact finite R graph" and saved.get("unrestricted_positive_cycle_length_claimed") is False,
        "certificate_gate_ok": saved.get("finite_check_certificate_issued") is True and saved.get("periodic_lift_classification_subcertificate_issued") is True and saved.get("appendix_i_combined_certificate_issued") is False,
        "no_edge_deletion_ok": saved.get("underlying_micrograph_edge_deletion_applied") is False,
        "status_ok": saved.get("status") == STATUS_PASS,
    }
    bound_check_names = [
        "bound_certificate_metadata_schema_ok",
        "bound_certificate_author_id_ok",
        "bound_certificate_generation_operator_id_ok",
        "bound_certificate_generation_operator_id_source_ok",
        "bound_certificate_created_at_present",
        "bound_certificate_generator_program_id_ok",
        "package_label_ok",
        "ids_ok",
        "bound_proof_content_ok",
        "bound_certificate_digest_ok",
        "graph_binding_ok",
        "maximum_cycle_length_ok",
        "bound_rows_exact_and_maximal",
        "global_bound_ok",
        "global_bound_argmax_ok",
        "bound_files_hash_ok",
        "no_edge_deletion_ok",
    ]
    bound_ok = all(checks.get(name, False) for name in bound_check_names)
    bound_status = STATUS_PASS if bound_ok else STATUS_FAIL
    bound = finalize_certificate(
        bound_cert_path,
        bound,
        verifier_program_id=__program_id__,
        verification_status=bound_status,
        digest_field="certificate_sha256",
    )
    bound_result = {
        "package_label": PACKAGE_LABEL,
        "M": M,
        "verification_status": bound_status,
        "overall_status": STATUS_PASS if bound_ok else STATUS_FAIL,
        "checks": {name: checks.get(name, False) for name in bound_check_names},
        **verification_record(bound),
        "verified_certificate_sha256": _sha_file(bound_cert_path),
        "verified_lengths_csv_sha256": _sha_file(bound_csv_path),
    }
    (bound_dir / "cycle_minimum_bound_verify_summary.json").write_text(
        json.dumps(bound_result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
    )

    final_bound_hash = _sha_file(bound_cert_path)
    if saved.get("minimum_bound_certificate_sha256") != final_bound_hash:
        saved["minimum_bound_certificate_sha256"] = final_bound_hash
        saved["audit_certificate_sha256"] = certificate_digest(saved, "audit_certificate_sha256")
        summary_path.write_text(
            json.dumps(saved, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
        )

    ok = all(checks.values()) and bound_ok
    status = STATUS_PASS if ok else STATUS_FAIL
    saved = finalize_certificate(summary_path, saved, verifier_program_id=__program_id__, verification_status=status, digest_field="audit_certificate_sha256")
    result = {
        "package_label": PACKAGE_LABEL, "M": M,
        "verification_status": status,
        "overall_status": STATUS_PASS if ok else STATUS_FAIL,
        "checks": checks,
        **verification_record(saved),
        "independent_mathematical_reconstruction_program_id": "LIC_independent_ch3_math",
        "independent_logical_graph_semantic_sha256": graph_semantic_hash,
        "rebuilt_global_minimum_value_bound": global_B,
        "rebuilt_total_odd_minimum_candidates": totals["candidates"],
        "rebuilt_final_candidate_evidence_sha256": previous,
        "verified_summary_sha256": _sha_file(summary_path),
        "verified_blocks_csv_sha256": _sha_file(blocks_path),
        "verified_bound_certificate_sha256": _sha_file(bound_cert_path),
        "verified_bound_lengths_csv_sha256": _sha_file(bound_csv_path),
    }
    (run_dir / "cycle_minimum_candidate_audit_verify_summary.json").write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    return result


if __name__ == "__main__":
    import argparse
    ap = argparse.ArgumentParser(); ap.add_argument("run_dir")
    ns = ap.parse_args(); print(json.dumps(verify_run(Path(ns.run_dir)), ensure_ascii=False, indent=2))

I.12.15 LIC_cycle_minimum_bound.py

#!/usr/bin/env python3
"""Exact minimum-value bounds for positive odd Collatz cycles.

Source metadata:
    File name: LIC_cycle_minimum_bound.py
    Program version: X04a
    Source file version: 1.0.2
    Created: 2026-07-29 23:55:10 JST
    Last updated: 2026-08-02 16:32:00 JST

Function summary:
    Computes the exact per-length minimum-value bound from the cycle product inequality, emits
    all length rows, and records the global maximum bound and its attaining length.

Remarks:
    The implementation uses exact integer arithmetic and an exact maximality check for every
    supported cycle length.
    Individual source-file versioning starts with this metadata revision. Earlier file-level
    changes are retained in package history but are not reconstructed as separate source-file
    versions.

Change history:
    - 1.0.2 / X04a / 2026-08-02 16:32:00 JST
      Updated X04a Program-membership metadata; executable logic is unchanged.
    - 1.0.1 / X03f / 2026-08-01 23:28:33 JST
      Updated the source metadata header for inclusion in the X03f Program package; executable logic is unchanged.
    - 1.0.0 / X03e / 2026-08-01 05:17:15 JST
      Added the standardized English source metadata header and established the
      initial individual source-file version baseline.

Detailed description:
    For a positive odd cycle of length L, let m=min_i V_i and S=sum_i T_i.
    The cycle product identity gives

        2^S = product_i (3 + 1/V_i) <= (3 + 1/m)^L.

    Moreover 3^L < 2^S, so S >= s_min(L)=bit_length(3^L).  Therefore

        2^s_min * m^L <= (3m+1)^L.

    The right-hand ratio 3+1/m is strictly decreasing in m, hence the largest
    integer m satisfying this inequality is an exact upper bound B_L.  Taking the
    maximum over all simple logical cycle lengths 1..N gives a finite global bound
    for the minimum value of every positive-integer periodic lift of an LP extreme
    cycle in the finite R graph.
"""
from __future__ import annotations

import csv
import hashlib
import json
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, Iterable, List, Tuple

from LIC_certificate_metadata import add_creation_metadata, certificate_digest
from LIC_r_logical_graph import build_r_logical_graph
from LIC_version import PACKAGE_LABEL, PACKAGE_VERSION
from LIC_status import STATUS_PASS

__program_id__ = "LIC_cycle_minimum_bound"
__version__ = PACKAGE_VERSION
THEOREM_ID = "LIC-POSITIVE-CYCLE-MINIMUM-BOUND-v2"


def _canonical_json(obj: object) -> bytes:
    return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")


def sha256_payload(obj: object) -> str:
    return hashlib.sha256(_canonical_json(obj)).hexdigest()


def sha256_file(path: Path) -> str:
    h = hashlib.sha256()
    with Path(path).open("rb") as f:
        for chunk in iter(lambda: f.read(1 << 20), b""):
            h.update(chunk)
    return h.hexdigest()


def logical_graph_sha256(M: int) -> Tuple[str, int, int]:
    graph = build_r_logical_graph(int(M))
    h = hashlib.sha256()
    h.update(f"M={M};odd={len(graph.odd_states)};edges={len(graph.edges)}\n".encode("ascii"))
    for edge in graph.edges:
        row = (
            int(edge.edge_id), int(edge.src.residue), int(edge.dst.residue), int(edge.t),
            int(edge.additional_division_cost), int(edge.transformed_weight),
            tuple(int(x) for x in edge.micro_edge_ids),
        )
        h.update(_canonical_json(row)); h.update(b"\n")
    return h.hexdigest(), len(graph.odd_states), len(graph.edges)


def critical_minimum_sum(length_L: int) -> int:
    L = int(length_L)
    if L <= 0:
        raise ValueError("length_L must be positive")
    return (3 ** L).bit_length()


def minimum_bound_inequality_holds(m: int, length_L: int, sum_T_min: int | None = None) -> bool:
    m = int(m); L = int(length_L)
    if m <= 0 or L <= 0:
        return False
    S = critical_minimum_sum(L) if sum_T_min is None else int(sum_T_min)
    return (1 << S) * pow(m, L) <= pow(3 * m + 1, L)


def exact_minimum_bound_for_length(length_L: int) -> Tuple[int, int]:
    L = int(length_L)
    S = critical_minimum_sum(L)
    lo = 0
    hi = 1
    while minimum_bound_inequality_holds(hi, L, S):
        lo = hi
        hi *= 2
    while lo + 1 < hi:
        mid = (lo + hi) // 2
        if minimum_bound_inequality_holds(mid, L, S):
            lo = mid
        else:
            hi = mid
    return S, lo


@dataclass(frozen=True)
class MinimumBoundRow:
    length_L: int
    critical_sum_T_min: int
    maximum_minimum_value_B_L: int
    bound_holds_at_B_L: bool
    bound_fails_at_B_L_plus_1: bool

    def as_dict(self) -> Dict[str, object]:
        return self.__dict__.copy()


def compute_minimum_bound_rows(max_length: int) -> Tuple[List[MinimumBoundRow], int, List[int]]:
    N = int(max_length)
    if N <= 0:
        raise ValueError("max_length must be positive")
    rows: List[MinimumBoundRow] = []
    global_bound = 0
    argmax: List[int] = []
    for L in range(1, N + 1):
        S, B = exact_minimum_bound_for_length(L)
        row = MinimumBoundRow(
            L, S, B,
            minimum_bound_inequality_holds(B, L, S),
            not minimum_bound_inequality_holds(B + 1, L, S),
        )
        rows.append(row)
        if B > global_bound:
            global_bound = B; argmax = [L]
        elif B == global_bound:
            argmax.append(L)
    return rows, global_bound, argmax


def write_minimum_bound_certificate(M: int, out_dir: Path) -> Dict[str, object]:
    M = int(M); out_dir = Path(out_dir); out_dir.mkdir(parents=True, exist_ok=True)
    graph_hash, odd_count, edge_count = logical_graph_sha256(M)
    if odd_count != M // 2:
        raise AssertionError("unexpected odd-state count")
    rows, global_bound, argmax = compute_minimum_bound_rows(odd_count)
    csv_path = out_dir / "cycle_minimum_bound_lengths.csv"
    with csv_path.open("w", encoding="utf-8", newline="") as f:
        w = csv.DictWriter(f, fieldnames=list(rows[0].as_dict()))
        w.writeheader(); w.writerows(r.as_dict() for r in rows)
    proof_steps = [
        "For every positive odd cycle, multiplication of 2^T_i V_(i+1)=3V_i+1 gives 2^S=product_i(3+1/V_i).",
        "With m=min_i V_i, every V_i>=m, hence 2^S<= (3+1/m)^L.",
        "The strict lower product bound gives 3^L<2^S, so S>=bit_length(3^L).",
        "Therefore 2^s_min*m^L <= (3m+1)^L is necessary.",
        "The function 3+1/m is strictly decreasing for positive m; the maximal integer satisfying the inequality is B_L.",
        "A simple logical R-cycle uses distinct odd states, so its length is at most the finite graph odd-state count N=M/2.",
        "Thus the minimum of every positive-integer periodic lift of an LP extreme cycle is at most max_(1<=L<=N) B_L.",
    ]
    core: Dict[str, object] = {
        "theorem_id": THEOREM_ID,
        "package_label": PACKAGE_LABEL,
        "M": M,
        "maximum_cycle_length": odd_count,
        "odd_state_count": odd_count,
        "logical_edge_count": edge_count,
        "logical_graph_sha256": graph_hash,
        "global_minimum_value_bound": global_bound,
        "global_bound_attained_at_lengths": argmax,
        "length_row_count": len(rows),
        "lengths_csv_sha256": sha256_file(csv_path),
        "proof_steps": proof_steps,
        "proof_sha256": sha256_payload(proof_steps),
        "scope": "positive-integer periodic lifts of simple logical R-cycles in the exact finite R graph",
        "underlying_micrograph_edge_deletion_applied": False,
        "status": STATUS_PASS,
    }
    add_creation_metadata(core, __program_id__)
    core["certificate_sha256"] = certificate_digest(core, "certificate_sha256")
    cert_path = out_dir / "cycle_minimum_bound_certificate.json"
    cert_path.write_text(json.dumps(core, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    report = [
        f"# Exact positive-cycle minimum bound — M={M}", "",
        f"- package: `{PACKAGE_LABEL}`",
        f"- status: **{core['status']}**",
        f"- maximum simple logical cycle length: `{odd_count}`",
        f"- global minimum-value candidate bound: `{global_bound}`",
        f"- bound attained at L: `{', '.join(map(str, argmax))}`",
        f"- logical graph SHA-256: `{graph_hash}`",
        f"- certificate SHA-256: `{core['certificate_sha256']}`",
    ]
    (out_dir / "cycle_minimum_bound_report.md").write_text("\n".join(report) + "\n", encoding="utf-8")
    return core


if __name__ == "__main__":
    import argparse
    ap = argparse.ArgumentParser(); ap.add_argument("--M", type=int, required=True); ap.add_argument("--out-dir", required=True)
    ns = ap.parse_args(); print(json.dumps(write_minimum_bound_certificate(ns.M, Path(ns.out_dir)), ensure_ascii=False, indent=2))

I.12.16 LIC_finite_lp_cycle_bridge.py

#!/usr/bin/env python3
"""Certificate bridge from finite circulation extrema to simple logical cycles.

Source metadata:
    File name: LIC_finite_lp_cycle_bridge.py
    Program version: X04a
    Source file version: 1.0.2
    Created: 2026-07-29 23:55:10 JST
    Last updated: 2026-08-02 16:32:00 JST

Function summary:
    Records the finite-graph binding and the maximum simple-cycle length needed to connect
    normalized finite circulation extreme points to simple directed logical cycles.

Remarks:
    This module records the structural bridge used by the finite-check workflow; it does not
    claim conclusions outside the selected finite graph.
    Individual source-file versioning starts with this metadata revision. Earlier file-level
    changes are retained in package history but are not reconstructed as separate source-file
    versions.

Change history:
    - 1.0.2 / X04a / 2026-08-02 16:32:00 JST
      Updated X04a Program-membership metadata; executable logic is unchanged.
    - 1.0.1 / X03f / 2026-08-01 23:28:33 JST
      Updated the source metadata header for inclusion in the X03f Program package; executable logic is unchanged.
    - 1.0.0 / X03e / 2026-08-01 05:17:15 JST
      Added the standardized English source metadata header and established the
      initial individual source-file version baseline.
"""
from __future__ import annotations

import hashlib
import json
from pathlib import Path
from typing import Dict

from LIC_certificate_metadata import add_creation_metadata, certificate_digest
from LIC_cycle_minimum_bound import logical_graph_sha256, sha256_payload
from LIC_version import PACKAGE_LABEL, PACKAGE_VERSION
from LIC_status import STATUS_PASS

__program_id__ = "LIC_finite_lp_cycle_bridge"
__version__ = PACKAGE_VERSION
BRIDGE_ID = "LIC-FINITE-CIRCULATION-EXTREME-CYCLE-BRIDGE-v2"


def theorem_payload(M: int) -> Dict[str, object]:
    graph_hash, N, E = logical_graph_sha256(int(M))
    proof_steps = [
        "A nonnegative normalized circulation on a finite directed graph decomposes into a convex combination of directed-cycle circulations.",
        "A linear objective over the normalized circulation polytope attains its minimum on an extreme point.",
        "Every extreme point is the normalized incidence circulation of a simple directed cycle.",
        "A simple logical R-cycle visits each odd finite state at most once.",
        "The exact R logical graph modulo M has M/2 odd finite states; therefore every LP extreme-cycle candidate has odd-transition length L<=M/2.",
    ]
    core: Dict[str, object] = {
        "bridge_id": BRIDGE_ID,
        "package_label": PACKAGE_LABEL,
        "M": int(M),
        "odd_state_count": N,
        "logical_edge_count": E,
        "maximum_simple_cycle_length": N,
        "logical_graph_sha256": graph_hash,
        "proof_steps": proof_steps,
        "proof_sha256": sha256_payload(proof_steps),
        "conclusions": {
            "lp_extreme_points_are_simple_cycle_circulations": True,
            "maximum_odd_transition_length": N,
            "underlying_edge_deletion_required": False,
        },
        "status": STATUS_PASS,
    }
    add_creation_metadata(core, __program_id__)
    core["certificate_sha256"] = certificate_digest(core, "certificate_sha256")
    return core


def write_certificate(M: int, out_dir: Path) -> Dict[str, object]:
    out_dir = Path(out_dir); out_dir.mkdir(parents=True, exist_ok=True)
    payload = theorem_payload(M)
    (out_dir / "finite_lp_cycle_bridge_certificate.json").write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    (out_dir / "finite_lp_cycle_bridge_report.md").write_text(
        f"# Finite LP extreme-cycle bridge — M={M}\n\n"
        f"- package: `{PACKAGE_LABEL}`\n"
        f"- status: **{payload['status']}**\n"
        f"- odd states: `{payload['odd_state_count']}`\n"
        f"- maximum simple cycle length: `{payload['maximum_simple_cycle_length']}`\n"
        f"- graph SHA-256: `{payload['logical_graph_sha256']}`\n",
        encoding="utf-8",
    )
    return payload

I.12.17 LIC_finite_lp_cycle_bridge_verifier.py

#!/usr/bin/env python3
"""Independent verifier for the finite-circulation and simple-cycle bridge.

Source metadata:
    File name: LIC_finite_lp_cycle_bridge_verifier.py
    Program version: X04a
    Source file version: 2.0.0
    Created: 2026-07-29 23:57:06 JST
    Last updated: 2026-08-02 16:32:00 JST

Function summary:
    Checks the target logical-graph binding, finite state count, simple-cycle length limit,
    metadata, evidence digest, and final bridge status.

Remarks:
    The verifier is independent of the bridge-certificate generator.
    Individual source-file versioning starts with this metadata revision. Earlier file-level
    changes are retained in package history but are not reconstructed as separate source-file
    versions.

Change history:
    - 2.0.0 / X04a / 2026-08-02 16:32:00 JST
      Replaced production logical-graph reconstruction with the independent Chapter 3 logical-edge enumerator.
    - 1.0.1 / X03f / 2026-08-01 23:28:33 JST
      Updated the source metadata header for inclusion in the X03f Program package; executable logic is unchanged.
    - 1.0.0 / X03e / 2026-08-01 05:17:15 JST
      Added the standardized English source metadata header and established the
      initial individual source-file version baseline.
"""
from __future__ import annotations

import hashlib
import json
from pathlib import Path
from typing import Dict

from LIC_certificate_metadata import certificate_digest, finalize_certificate, metadata_checks, verification_record
from LIC_independent_ch3_math import logical_graph_record
from LIC_version import PACKAGE_LABEL, PACKAGE_VERSION
from LIC_status import STATUS_FAIL, STATUS_PASS

__program_id__ = "LIC_finite_lp_cycle_bridge_verifier"
__version__ = PACKAGE_VERSION


def _canonical(obj: object) -> bytes:
    return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")


def _digest(obj: object) -> str:
    return hashlib.sha256(_canonical(obj)).hexdigest()


def _sha(path: Path) -> str:
    h = hashlib.sha256()
    with Path(path).open("rb") as f:
        for b in iter(lambda: f.read(1 << 20), b""):
            h.update(b)
    return h.hexdigest()


def verify_run(run_dir: Path) -> Dict[str, object]:
    run_dir = Path(run_dir); p = run_dir / "finite_lp_cycle_bridge_certificate.json"
    saved = json.loads(p.read_text(encoding="utf-8")); M = int(saved["M"])
    independent_graph = logical_graph_record(M)
    graph_hash = str(independent_graph["sha256"])
    N = int(independent_graph["odd_state_count"])
    E = int(independent_graph["logical_edge_count"])
    expected_steps = [
        "A nonnegative normalized circulation on a finite directed graph decomposes into a convex combination of directed-cycle circulations.",
        "A linear objective over the normalized circulation polytope attains its minimum on an extreme point.",
        "Every extreme point is the normalized incidence circulation of a simple directed cycle.",
        "A simple logical R-cycle visits each odd finite state at most once.",
        "The exact R logical graph modulo M has M/2 odd finite states; therefore every LP extreme-cycle candidate has odd-transition length L<=M/2.",
    ]
    checks = {
        **metadata_checks(saved, "LIC_finite_lp_cycle_bridge"),
        "package_label_ok": saved.get("package_label") == PACKAGE_LABEL,
        "bridge_id_ok": saved.get("bridge_id") == "LIC-FINITE-CIRCULATION-EXTREME-CYCLE-BRIDGE-v2",
        "graph_binding_ok": saved.get("logical_graph_sha256") == graph_hash and int(saved.get("odd_state_count", -1)) == N and int(saved.get("logical_edge_count", -1)) == E,
        "length_bound_ok": int(saved.get("maximum_simple_cycle_length", -1)) == N == M // 2,
        "proof_content_ok": saved.get("proof_steps") == expected_steps and saved.get("proof_sha256") == _digest(expected_steps),
        "conclusions_ok": saved.get("conclusions") == {"lp_extreme_points_are_simple_cycle_circulations": True, "maximum_odd_transition_length": N, "underlying_edge_deletion_required": False},
        "certificate_digest_ok": saved.get("certificate_sha256") == certificate_digest(saved, "certificate_sha256"),
        "status_ok": saved.get("status") == STATUS_PASS,
    }
    ok = all(checks.values())
    status = STATUS_PASS if ok else STATUS_FAIL
    saved = finalize_certificate(p, saved, verifier_program_id=__program_id__, verification_status=status, digest_field="certificate_sha256")
    result = {"package_label": PACKAGE_LABEL, "M": M, "verification_status": status, "overall_status": STATUS_PASS if ok else STATUS_FAIL, "checks": checks, **verification_record(saved),
        "independent_mathematical_reconstruction_program_id": "LIC_independent_ch3_math",
        "independent_logical_graph_semantic_sha256": independent_graph["semantic_sha256"],
        "verified_certificate_sha256": _sha(p)}
    (run_dir / "finite_lp_cycle_bridge_verify_summary.json").write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    return result

I.12.18 LIC_phase_b_structure.py

#!/usr/bin/env python3
"""All-length structural certificate for the Phase-B inequality.

Source metadata:
    File name: LIC_phase_b_structure.py
    Program version: X04a
    Source file version: 1.0.2
    Created: 2026-07-29 23:55:10 JST
    Last updated: 2026-08-02 16:32:00 JST

Function summary:
    Constructs the exact all-length structural theorem payload, classifies objective windows and
    ordered division patterns, and identifies the trivial positive odd cycle structure.

Remarks:
    The theorem payload uses exact arithmetic and is a structural child certificate within the
    complete classification workflow.
    Individual source-file versioning starts with this metadata revision. Earlier file-level
    changes are retained in package history but are not reconstructed as separate source-file
    versions.

Change history:
    - 1.0.2 / X04a / 2026-08-02 16:32:00 JST
      Updated X04a Program-membership metadata; executable logic is unchanged.
    - 1.0.1 / X03f / 2026-08-01 23:28:33 JST
      Updated the source metadata header for inclusion in the X03f Program package; executable logic is unchanged.
    - 1.0.0 / X03e / 2026-08-01 05:17:15 JST
      Added the standardized English source metadata header and established the
      initial individual source-file version baseline.

Detailed description:
    For a positive odd Collatz cycle V_0,...,V_{L-1}, with

        2^{T_i} V_{i+1} = 3 V_i + 1,

    multiplication around the cycle gives

        2^S = product_i (3 + 1/V_i),  S = sum_i T_i.

    Since every V_i is a positive integer, every factor is strictly greater than 3
    and at most 4. Hence 3^L < 2^S <= 4^L, so
    log_2(3/2) < lambda_x <= 1. Equality at the upper endpoint requires V_i = 1
    for every i, and therefore T_i = 2 for every i. Thus:

    * lambda_x <= log_2(3/2): no positive-integer periodic orbit exists;
    * log_2(3/2) < lambda_x < 1: the only unresolved objective window;
    * lambda_x > 1: no positive-integer periodic orbit exists;
    * lambda_x = 1: the only positive-integer periodic orbit is the trivial 1-loop.

    This theorem is independent of M and of cycle length. It aggregates the entire
    Phase-B search space without enumerating individual closed-walk families.
"""
from __future__ import annotations

from dataclasses import dataclass
import hashlib
import json
from pathlib import Path
from typing import Dict, Mapping, Optional, Sequence, Tuple

from LIC_certificate_metadata import add_creation_metadata, certificate_digest
from LIC_version import PACKAGE_LABEL, PACKAGE_VERSION
from LIC_status import STATUS_PASS

__program_id__ = "LIC_phase_b_structure"
__version__ = PACKAGE_VERSION
THEOREM_ID = "LIC-POSITIVE-CYCLE-OBJECTIVE-WINDOW-v2"


def _canonical_json(obj: object) -> bytes:
    return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")


def sha256_payload(obj: object) -> str:
    return hashlib.sha256(_canonical_json(obj)).hexdigest()


@dataclass(frozen=True)
class PhaseBPatternResult:
    ordered_t_pattern: Tuple[int, ...]
    length_L: int
    sum_T: int
    additional_division_total: int
    objective_numerator: int
    objective_denominator: int
    phase_bucket: str
    structural_status: str
    structural_reason: str
    equality_pattern_all_t2: bool

    def as_dict(self) -> Dict[str, object]:
        return {
            "ordered_t_pattern": list(self.ordered_t_pattern),
            "length_L": self.length_L,
            "sum_T": self.sum_T,
            "additional_division_total": self.additional_division_total,
            "objective_numerator": self.objective_numerator,
            "objective_denominator": self.objective_denominator,
            "phase_bucket": self.phase_bucket,
            "structural_status": self.structural_status,
            "structural_reason": self.structural_reason,
            "equality_pattern_all_t2": self.equality_pattern_all_t2,
        }


def objective_window_bounds(length_L: int) -> Tuple[int, int]:
    """Return integer S bounds for 3^L < 2^S < 4^L."""
    L = int(length_L)
    if L <= 0:
        raise ValueError("length_L must be positive")
    return (3 ** L).bit_length(), 2 * L - 1


def classify_objective_window(pattern: Sequence[int]) -> Dict[str, object]:
    t = tuple(int(x) for x in pattern)
    if not t or any(x < 1 for x in t):
        raise ValueError("pattern must be a nonempty sequence of positive T values")
    L = len(t); S = sum(t); p2 = 1 << S; p3 = 3 ** L; p4 = 1 << (2 * L)
    if p2 <= p3:
        bucket = "BELOW_OR_EQUAL_LOWER_BOUND"
        status = "PERIODIC_CLOSURE_FORBIDDEN"
        reason = "positive_integer_cycle_product_lower_bound_2S_le_3L"
    elif p2 < p4:
        bucket = "CRITICAL_OPEN_WINDOW"
        status = "REQUIRES_PATTERN_SPECIFIC_CLASSIFICATION"
        reason = "3L_lt_2S_lt_4L"
    elif p2 == p4:
        bucket = "UPPER_EQUALITY"
        status = "EQUALITY_REQUIRES_TRIVIAL_ORBIT" if all(x == 2 for x in t) else "PERIODIC_CLOSURE_FORBIDDEN"
        reason = "S_equals_2L_implies_all_cycle_values_equal_1" if all(x == 2 for x in t) else "S_equals_2L_but_pattern_not_all_2"
    else:
        bucket = "ABOVE_UPPER_BOUND"
        status = "PERIODIC_CLOSURE_FORBIDDEN"
        reason = "positive_integer_cycle_product_upper_bound_2S_gt_4L"
    return {
        "ordered_t_pattern": list(t), "length_L": L, "sum_T": S,
        "additional_division_total": S-L, "objective_numerator": S-L, "objective_denominator": L,
        "objective_window_bucket": bucket, "structural_status": status, "structural_reason": reason,
        "critical_sum_T_min": objective_window_bounds(L)[0], "critical_sum_T_max": objective_window_bounds(L)[1],
    }


def classify_phase_b_pattern(pattern: Sequence[int]) -> PhaseBPatternResult:
    t = tuple(int(x) for x in pattern)
    w = classify_objective_window(t)
    L = int(w["length_L"]); S = int(w["sum_T"]); add = S-L
    if S < 2*L:
        phase = "PHASE_A_SUBUNIT"
        status = str(w["structural_status"])
        reason = str(w["structural_reason"])
    elif S > 2*L:
        phase = "PHASE_B_ABOVE_UNIT"
        status = str(w["structural_status"])
        reason = str(w["structural_reason"])
    else:
        phase = "PHASE_B_UNIT"
        status = str(w["structural_status"]); reason = str(w["structural_reason"])
    return PhaseBPatternResult(t,L,S,add,add,L,phase,status,reason,all(x==2 for x in t))


def is_trivial_phase_b_cycle(graph, logical_edge_ids: Sequence[int]) -> bool:
    ids = tuple(int(x) for x in logical_edge_ids)
    if len(ids) != 1:
        return False
    e = graph.edges_by_id[ids[0]]
    return (
        e.t == 2
        and int(e.src.residue) == 1
        and int(e.dst.residue) == 1
    )


def classify_phase_b_cycle(graph, logical_edge_ids: Sequence[int]) -> Dict[str, object]:
    ids = tuple(int(x) for x in logical_edge_ids)
    pattern = tuple(graph.edges_by_id[x].t for x in ids)
    p = classify_phase_b_pattern(pattern)
    d = p.as_dict()
    d["logical_edge_ids"] = list(ids)
    if p.phase_bucket == "PHASE_A_SUBUNIT":
        d.update({
            "family_role": "OUT_OF_SCOPE_PHASE_A",
            "positive_integer_periodic": None,
            "trivial_loop": False,
        })
        return d
    trivial = p.structural_status == "EQUALITY_REQUIRES_TRIVIAL_ORBIT" and is_trivial_phase_b_cycle(graph, ids)
    d.update({
        "family_role": "POSITIVE_INTEGER_PERIODIC" if trivial else "PERIODIC_CLOSURE_FORBIDDEN",
        "positive_integer_periodic": trivial,
        "trivial_loop": trivial,
        "structural_status": "POSITIVE_INTEGER_PERIODIC_TRIVIAL_ONLY" if trivial else "PERIODIC_CLOSURE_FORBIDDEN",
        "structural_reason": "trivial_1_loop_equality_case" if trivial else p.structural_reason,
    })
    return d


def theorem_payload() -> Dict[str, object]:
    proof_steps = [
        {
            "step": 1,
            "statement": "For each odd transition, 2^T_i * V_(i+1) = 3*V_i + 1.",
        },
        {
            "step": 2,
            "statement": "Multiplying around a periodic orbit and cancelling product(V_i) gives 2^S = product_i(3 + 1/V_i).",
        },
        {
            "step": 3,
            "statement": "V_i >= 1 implies 3 < 3 + 1/V_i <= 4, hence 3^L < 2^S <= 4^L.",
        },
        {
            "step": 4,
            "statement": "lambda_x = (S-L)/L, hence log_2(3/2) < lambda_x <= 1.",
        },
        {
            "step": 5,
            "statement": "Equality S=2L requires every factor 3+1/V_i=4, so every V_i=1 and every T_i=2.",
        },
    ]
    core = {
        "theorem_id": THEOREM_ID,
        "package_label": PACKAGE_LABEL,
        "scope": "all positive-integer odd Collatz periodic orbits; all lengths; all powers-of-two M",
        "assumptions": [
            "L is a positive integer",
            "V_i are positive odd integers with cyclic indexing",
            "T_i are positive integers satisfying 2^T_i V_(i+1)=3V_i+1",
        ],
        "proof_steps": proof_steps,
        "conclusions": {
            "below_or_equal_alpha_star": "periodic_closure_forbidden",
            "critical_open_window": "log2(3/2) < lambda_x < 1",
            "phase_B_above_unit": "periodic_closure_forbidden",
            "phase_B_unit": "trivial_1_loop_only",
            "all_length_lower_and_phase_B_complete": True,
            "all_length_phase_B_complete": True,
            "underlying_graph_edge_deletion_required": False,
            "individual_phase_B_family_enumeration_required": False,
        },
    }
    core["proof_sha256"] = sha256_payload(proof_steps)
    core["lower_window_status"] = STATUS_PASS
    core["phase_b_status"] = STATUS_PASS
    core["status"] = STATUS_PASS
    add_creation_metadata(core, __program_id__)
    core["certificate_sha256"] = certificate_digest(core, "certificate_sha256")
    return core


def write_certificate(out_dir: Path) -> Dict[str, object]:
    out_dir.mkdir(parents=True, exist_ok=True)
    payload = theorem_payload()
    (out_dir / "phase_b_structure_certificate.json").write_text(
        json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
    )
    report = [
        "# LIC X02 all-length positive-cycle objective-window certificate",
        "",
        f"- package: `{PACKAGE_LABEL}`",
        f"- theorem: `{THEOREM_ID}`",
        f"- status: **{payload['status']}**",
        "- scope: all positive-integer periodic odd Collatz orbits, all lengths and all powers-of-two M",
        "- lambda_x <= log2(3/2): impossible",
        "- log2(3/2) < lambda_x < 1: unresolved critical open window",
        "- Phase B with lambda_x > 1: impossible",
        "- Phase B with lambda_x = 1: trivial 1-loop only",
        "- individual Phase-B family enumeration: not required",
        "- underlying edge deletion: not used",
        "",
        "The proof multiplies the exact odd-transition identities around the cycle,",
        "obtains 2^S = product_i(3 + 1/V_i), and uses 3 < 3 + 1/V_i <= 4.",
    ]
    (out_dir / "phase_b_structure_report.md").write_text("\n".join(report) + "\n", encoding="utf-8")
    return payload

I.12.19 LIC_phase_b_structure_verifier.py

#!/usr/bin/env python3
"""Independent verifier for the all-length Phase-B structural certificate.

Source metadata:
    File name: LIC_phase_b_structure_verifier.py
    Program version: X04a
    Source file version: 2.0.0
    Created: 2026-07-29 23:55:10 JST
    Last updated: 2026-08-02 16:32:00 JST

Function summary:
    Recomputes the theorem payload, verifies metadata and file identity, and checks that the
    recorded structural classification and status are exact.

Remarks:
    The verifier does not rely on the generator implementation to establish the theorem payload.
    Individual source-file versioning starts with this metadata revision. Earlier file-level
    changes are retained in package history but are not reconstructed as separate source-file
    versions.

Change history:
    - 2.0.0 / X04a / 2026-08-02 16:32:00 JST
      Replaced generator theorem-payload reuse with a verifier-owned theorem specification.
    - 1.0.1 / X03f / 2026-08-01 23:28:33 JST
      Updated the source metadata header for inclusion in the X03f Program package; executable logic is unchanged.
    - 1.0.0 / X03e / 2026-08-01 05:17:15 JST
      Added the standardized English source metadata header and established the
      initial individual source-file version baseline.
"""
from __future__ import annotations

import hashlib
import json
from pathlib import Path
from typing import Dict

from LIC_certificate_metadata import certificate_digest, finalize_certificate, metadata_checks, verification_record
from LIC_independent_ch3_math import PHASE_B_THEOREM_ID, phase_b_theorem_specification
from LIC_version import PACKAGE_LABEL, PACKAGE_VERSION
from LIC_status import STATUS_FAIL, STATUS_PASS

__program_id__ = "LIC_phase_b_structure_verifier"
__version__ = PACKAGE_VERSION


def _sha(path: Path) -> str:
    h = hashlib.sha256()
    with path.open("rb") as f:
        for chunk in iter(lambda: f.read(1 << 20), b""):
            h.update(chunk)
    return h.hexdigest()


def verify_run(run_dir: Path) -> Dict[str, object]:
    cert_path = run_dir / "phase_b_structure_certificate.json"
    saved = json.loads(cert_path.read_text(encoding="utf-8"))
    rebuilt = phase_b_theorem_specification()
    checks = {
        **metadata_checks(saved, "LIC_phase_b_structure"),
        "theorem_id_ok": saved.get("theorem_id") == PHASE_B_THEOREM_ID,
        "package_label_ok": saved.get("package_label") == PACKAGE_LABEL,
        "proof_steps_exact_match": saved.get("proof_steps") == rebuilt.get("proof_steps"),
        "assumptions_exact_match": saved.get("assumptions") == rebuilt.get("assumptions"),
        "conclusions_exact_match": saved.get("conclusions") == rebuilt.get("conclusions"),
        "proof_sha256_ok": saved.get("proof_sha256") == rebuilt.get("proof_sha256"),
        "certificate_sha256_ok": saved.get("certificate_sha256") == certificate_digest(saved, "certificate_sha256"),
        "all_length_scope_ok": saved.get("conclusions", {}).get("all_length_phase_B_complete") is True,
        "all_length_lower_bound_scope_ok": saved.get("conclusions", {}).get("all_length_lower_and_phase_B_complete") is True,
        "no_edge_deletion_ok": saved.get("conclusions", {}).get("underlying_graph_edge_deletion_required") is False,
        "no_family_enumeration_ok": saved.get("conclusions", {}).get("individual_phase_B_family_enumeration_required") is False,
        "lower_window_status_ok": saved.get("lower_window_status") == STATUS_PASS,
        "phase_b_status_ok": saved.get("phase_b_status") == STATUS_PASS,
        "status_ok": saved.get("status") == STATUS_PASS,
    }
    ok = all(checks.values())
    status = STATUS_PASS if ok else STATUS_FAIL
    saved = finalize_certificate(cert_path, saved, verifier_program_id=__program_id__, verification_status=status, digest_field="certificate_sha256")
    result = {
        "package_label": PACKAGE_LABEL,
        "theorem_id": PHASE_B_THEOREM_ID,
        "verification_status": status,
        "overall_status": STATUS_PASS if ok else STATUS_FAIL,
        "checks": checks,
        **verification_record(saved),
        "verified_certificate_file_sha256": _sha(cert_path),
        "rebuilt_certificate_sha256": certificate_digest(saved, "certificate_sha256"),
    }
    (run_dir / "phase_b_structure_verify_summary.json").write_text(
        json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
    )
    return result

I.12.20 LIC_r_logical_graph.py

#!/usr/bin/env python3
"""Finite odd-boundary logical graph derived from the exact R-micrograph.

Source metadata:
    File name: LIC_r_logical_graph.py
    Program version: X04a
    Source file version: 1.0.2
    Created: 2026-07-23 15:56:26 JST
    Last updated: 2026-08-02 16:32:00 JST

Function summary:
    Collapses simple odd-to-odd micrograph paths into labeled logical edges and provides
    validation and lifting helpers between logical cycles and microedge sequences.

Remarks:
    Logical edges retain their ordered microedge sequences so independent verification can bind
    them to the exact R-micrograph.
    Individual source-file versioning starts with this metadata revision. Earlier file-level
    changes are retained in package history but are not reconstructed as separate source-file
    versions.

Change history:
    - 1.0.2 / X04a / 2026-08-02 16:32:00 JST
      Updated X04a Program-membership metadata; executable logic is unchanged.
    - 1.0.1 / X03f / 2026-08-01 23:28:33 JST
      Updated the source metadata header for inclusion in the X03f Program package; executable logic is unchanged.
    - 1.0.0 / X03e / 2026-08-01 05:17:15 JST
      Added the standardized English source metadata header and established the
      initial individual source-file version baseline.

Detailed description:
    Each logical edge is one simple ODD-to-ODD path through the micrograph.  A
    simple normalized microcycle can use only such paths; paths that repeat an
    internal microstate are not needed for extreme-cycle enumeration.
"""
from __future__ import annotations

from dataclasses import dataclass
from typing import Dict, List, Mapping, Sequence, Tuple

from LIC_r_micrograph import PHASE_ODD, MicroState, RMicroGraph, build_r_micrograph
from LIC_version import PACKAGE_LABEL, PACKAGE_VERSION

__program_id__ = "LIC_r_logical_graph"
__version__ = PACKAGE_VERSION


@dataclass(frozen=True)
class LogicalREdge:
    edge_id: int
    src: MicroState
    dst: MicroState
    t: int
    additional_division_cost: int
    transformed_weight: int
    micro_edge_ids: Tuple[int, ...]

    def as_dict(self):
        return {
            "edge_id": self.edge_id,
            "src": self.src.as_dict(),
            "dst": self.dst.as_dict(),
            "t": self.t,
            "additional_division_cost": self.additional_division_cost,
            "transformed_weight": self.transformed_weight,
            "micro_edge_ids": list(self.micro_edge_ids),
        }


@dataclass(frozen=True)
class RLogicalGraph:
    package_label: str
    M: int
    micrograph: RMicroGraph
    odd_states: Tuple[MicroState, ...]
    edges: Tuple[LogicalREdge, ...]
    edges_by_id: Mapping[int, LogicalREdge]
    outgoing: Mapping[MicroState, Tuple[LogicalREdge, ...]]

    def as_dict(self):
        return {
            "package_label": self.package_label,
            "M": self.M,
            "odd_state_count": len(self.odd_states),
            "logical_edge_count": len(self.edges),
            "max_t": max((e.t for e in self.edges), default=0),
        }


def build_r_logical_graph(M: int) -> RLogicalGraph:
    mg = build_r_micrograph(M)
    out: List[LogicalREdge] = []
    eid = 0
    for root in sorted(mg.odd_states):
        first_edges = mg.outgoing[root]
        if len(first_edges) != 1:
            raise AssertionError("odd microstate must have exactly one 3n+1 edge")
        first = first_edges[0]
        # state, path edge IDs, visited nonterminal microstates, division count
        stack = [(first.dst, (first.edge_id,), frozenset((root, first.dst)), 0)]
        while stack:
            state, path, visited, t = stack.pop()
            for me in mg.outgoing[state]:
                nt = t + 1
                npath = path + (me.edge_id,)
                if me.dst.phase == PHASE_ODD:
                    out.append(LogicalREdge(
                        eid, root, me.dst, nt, nt - 1, nt - 2, npath
                    ))
                    eid += 1
                elif me.dst not in visited:
                    stack.append((me.dst, npath, visited | frozenset((me.dst,)), nt))
    by_id = {e.edge_id: e for e in out}
    outgoing_lists: Dict[MicroState, List[LogicalREdge]] = {s: [] for s in mg.odd_states}
    for e in out:
        outgoing_lists[e.src].append(e)
    outgoing = {s: tuple(sorted(v, key=lambda e: e.edge_id)) for s, v in outgoing_lists.items()}
    return RLogicalGraph(PACKAGE_LABEL, M, mg, tuple(sorted(mg.odd_states)), tuple(out), by_id, outgoing)


def logical_cycle_to_micro_edges(graph: RLogicalGraph, logical_edge_ids: Sequence[int]) -> Tuple[int, ...]:
    ids: List[int] = []
    for eid in logical_edge_ids:
        ids.extend(graph.edges_by_id[int(eid)].micro_edge_ids)
    return tuple(ids)


def validate_simple_logical_cycle(graph: RLogicalGraph, logical_edge_ids: Sequence[int]) -> Tuple[bool, str]:
    if not logical_edge_ids:
        return False, "empty_cycle"
    les = [graph.edges_by_id[int(x)] for x in logical_edge_ids]
    for a, b in zip(les, les[1:] + les[:1]):
        if a.dst != b.src:
            return False, "logical_cycle_disconnected"
    odd_vertices = [e.src for e in les]
    if len(set(odd_vertices)) != len(odd_vertices):
        return False, "odd_state_repeated"
    micro_ids = logical_cycle_to_micro_edges(graph, logical_edge_ids)
    mes = [graph.micrograph.edges_by_id[x] for x in micro_ids]
    if not mes or mes[-1].dst != mes[0].src:
        return False, "micro_cycle_not_closed"
    states = [mes[0].src] + [e.dst for e in mes]
    if states[-1] != states[0]:
        return False, "micro_cycle_not_closed"
    if len(set(states[:-1])) != len(states) - 1:
        return False, "internal_microstate_overlap"
    return True, "PASS"

I.12.21 LIC_r_micrograph.py

#!/usr/bin/env python3
"""Finite internal micrograph for exact R-block transitions.

Source metadata:
    File name: LIC_r_micrograph.py
    Program version: X04a
    Source file version: 1.0.2
    Created: 2026-07-23 15:56:26 JST
    Last updated: 2026-08-02 16:32:00 JST

Function summary:
    Builds the finite microstate graph for a power-of-two modulus, traces exact witnesses,
    validates micro-paths, and lifts paths to exact odd-to-odd R-transition evidence.

Remarks:
    The micrograph is an internal finite representation. The externally visible mathematical
    transition remains the exact odd-to-odd R-transition.
    Individual source-file versioning starts with this metadata revision. Earlier file-level
    changes are retained in package history but are not reconstructed as separate source-file
    versions.

Change history:
    - 1.0.2 / X04a / 2026-08-02 16:32:00 JST
      Updated X04a Program-membership metadata; executable logic is unchanged.
    - 1.0.1 / X03f / 2026-08-01 23:28:33 JST
      Updated the source metadata header for inclusion in the X03f Program package; executable logic is unchanged.
    - 1.0.0 / X03e / 2026-08-01 05:17:15 JST
      Added the standardized English source metadata header and established the
      initial individual source-file version baseline.

Detailed description:
    The graph is finite for each power-of-two modulus M.  A complete path from an
    ODD state to the next ODD state represents one exact odd-to-odd Collatz R(n)
    transition.  The externally visible mathematical unit remains the logical
    R-edge from ``LIC_r_transition``.
"""
from __future__ import annotations

from dataclasses import asdict, dataclass
from typing import Dict, Iterable, List, Mapping, Optional, Sequence, Tuple

from LIC_constants import R_TRANSITION_MODEL_EXACT_LOGICAL_EDGE
from LIC_r_transition import (
    LogicalREdge,
    RTransitionError,
    make_logical_r_edge,
)
from LIC_version import PACKAGE_LABEL, PACKAGE_VERSION

__program_id__ = "LIC_r_micrograph"
__version__ = PACKAGE_VERSION

PHASE_ODD = "ODD_BOUNDARY"
PHASE_AFTER_3N_PLUS_1 = "AFTER_3N_PLUS_1"
PHASE_DIVISION_CONTINUE = "DIVISION_CONTINUE"
OP_3N_PLUS_1 = "APPLY_3N_PLUS_1"
OP_FIRST_DIVIDE_BY_2 = "FIRST_DIVIDE_BY_2"
OP_EXTRA_DIVIDE_BY_2 = "EXTRA_DIVIDE_BY_2"


@dataclass(frozen=True, order=True)
class MicroState:
    phase: str
    residue: int

    def as_dict(self) -> Dict[str, object]:
        return asdict(self)


@dataclass(frozen=True)
class MicroEdge:
    edge_id: int
    src: MicroState
    dst: MicroState
    operation: str
    odd_transition_count: int
    additional_division_cost: int

    def as_dict(self) -> Dict[str, object]:
        d = asdict(self)
        return d


@dataclass(frozen=True)
class RBlockTrace:
    package_label: str
    transition_model: str
    M: int
    witness: int
    start_state: MicroState
    end_state: MicroState
    micro_edge_ids: Tuple[int, ...]
    division_count: int
    additional_division_cost: int
    logical_edge: LogicalREdge

    def as_dict(self) -> Dict[str, object]:
        return {
            "package_label": self.package_label,
            "transition_model": self.transition_model,
            "M": self.M,
            "witness": self.witness,
            "start_state": self.start_state.as_dict(),
            "end_state": self.end_state.as_dict(),
            "micro_edge_ids": list(self.micro_edge_ids),
            "division_count": self.division_count,
            "additional_division_cost": self.additional_division_cost,
            "logical_edge": self.logical_edge.as_dict(),
        }


@dataclass(frozen=True)
class RMicroGraph:
    M: int
    states: Tuple[MicroState, ...]
    edges: Tuple[MicroEdge, ...]
    edge_lookup: Mapping[Tuple[MicroState, MicroState, str], MicroEdge]
    edges_by_id: Mapping[int, MicroEdge]
    outgoing: Mapping[MicroState, Tuple[MicroEdge, ...]]

    @property
    def odd_states(self) -> Tuple[MicroState, ...]:
        return tuple(s for s in self.states if s.phase == PHASE_ODD)


def _require_power_of_two_modulus(M: int) -> int:
    if isinstance(M, bool) or not isinstance(M, int) or M < 4 or (M & (M - 1)):
        raise RTransitionError(f"micrograph modulus M must be a power of two >= 4, got {M!r}")
    return M


def _division_destinations(residue: int, M: int) -> Tuple[int, int]:
    if residue % 2 != 0:
        raise RTransitionError(f"division source residue must be even, got {residue}")
    low = residue // 2
    high = low + M // 2
    return low, high


def _phase_for_quotient(residue: int) -> str:
    return PHASE_ODD if residue % 2 == 1 else PHASE_DIVISION_CONTINUE


def build_r_micrograph(M: int) -> RMicroGraph:
    """Construct the complete finite internal graph for one modulus M."""
    M = _require_power_of_two_modulus(M)
    odd_residues = tuple(range(1, M, 2))
    even_residues = tuple(range(0, M, 2))
    states = tuple(
        [MicroState(PHASE_ODD, r) for r in odd_residues]
        + [MicroState(PHASE_AFTER_3N_PLUS_1, r) for r in even_residues]
        + [MicroState(PHASE_DIVISION_CONTINUE, r) for r in even_residues]
    )

    edges: List[MicroEdge] = []
    eid = 0
    for s in odd_residues:
        src = MicroState(PHASE_ODD, s)
        dst = MicroState(PHASE_AFTER_3N_PLUS_1, (3 * s + 1) % M)
        edges.append(MicroEdge(eid, src, dst, OP_3N_PLUS_1, 1, 0))
        eid += 1

    for phase, operation, cost in (
        (PHASE_AFTER_3N_PLUS_1, OP_FIRST_DIVIDE_BY_2, 0),
        (PHASE_DIVISION_CONTINUE, OP_EXTRA_DIVIDE_BY_2, 1),
    ):
        for r in even_residues:
            src = MicroState(phase, r)
            for q in _division_destinations(r, M):
                dst = MicroState(_phase_for_quotient(q), q)
                edges.append(MicroEdge(eid, src, dst, operation, 0, cost))
                eid += 1

    lookup: Dict[Tuple[MicroState, MicroState, str], MicroEdge] = {}
    outgoing_lists: Dict[MicroState, List[MicroEdge]] = {s: [] for s in states}
    for e in edges:
        key = (e.src, e.dst, e.operation)
        if key in lookup:
            raise AssertionError(f"duplicate micro edge key {key!r}")
        lookup[key] = e
        outgoing_lists[e.src].append(e)
    outgoing = {s: tuple(v) for s, v in outgoing_lists.items()}
    edges_by_id = {e.edge_id: e for e in edges}

    expected_states = 3 * M // 2
    expected_edges = 5 * M // 2
    if len(states) != expected_states:
        raise AssertionError(f"state count mismatch {len(states)} != {expected_states}")
    if len(edges) != expected_edges:
        raise AssertionError(f"edge count mismatch {len(edges)} != {expected_edges}")
    return RMicroGraph(M, states, tuple(edges), lookup, edges_by_id, outgoing)


def _find_edge(graph: RMicroGraph, src: MicroState, dst: MicroState, operation: str) -> MicroEdge:
    try:
        return graph.edge_lookup[(src, dst, operation)]
    except KeyError as exc:
        raise RTransitionError(
            f"micro edge missing: src={src!r} dst={dst!r} operation={operation}"
        ) from exc


def trace_witness(graph: RMicroGraph, n: int) -> RBlockTrace:
    """Trace one concrete positive odd witness through the finite micrograph."""
    logical = make_logical_r_edge(n, graph.M)
    state = MicroState(PHASE_ODD, logical.src)
    start = state
    ids: List[int] = []

    value = 3 * n + 1
    next_state = MicroState(PHASE_AFTER_3N_PLUS_1, value % graph.M)
    edge = _find_edge(graph, state, next_state, OP_3N_PLUS_1)
    ids.append(edge.edge_id)
    state = next_state

    t = 0
    additional_cost = 0
    while value % 2 == 0:
        value //= 2
        t += 1
        operation = OP_FIRST_DIVIDE_BY_2 if t == 1 else OP_EXTRA_DIVIDE_BY_2
        next_state = MicroState(_phase_for_quotient(value % graph.M), value % graph.M)
        edge = _find_edge(graph, state, next_state, operation)
        ids.append(edge.edge_id)
        additional_cost += edge.additional_division_cost
        state = next_state

    if state.phase != PHASE_ODD:
        raise AssertionError("completed exact R-transition did not end at ODD_BOUNDARY")
    if t != logical.t or value != logical.next_odd:
        raise AssertionError("microtrace does not match logical R-edge")
    if additional_cost != logical.additional_divisions:
        raise AssertionError("microtrace cost does not match T-1")
    return RBlockTrace(
        package_label=PACKAGE_LABEL,
        transition_model=R_TRANSITION_MODEL_EXACT_LOGICAL_EDGE,
        M=graph.M,
        witness=n,
        start_state=start,
        end_state=state,
        micro_edge_ids=tuple(ids),
        division_count=t,
        additional_division_cost=additional_cost,
        logical_edge=logical,
    )


def verify_trace(graph: RMicroGraph, trace: RBlockTrace) -> Tuple[bool, str]:
    """Recompute a witness trace and compare all externally meaningful fields."""
    try:
        expected = trace_witness(graph, trace.witness)
    except Exception as exc:
        return False, f"recompute_error:{type(exc).__name__}:{exc}"
    if trace != expected:
        return False, f"trace_mismatch:expected={expected!r}:actual={trace!r}"
    return True, "PASS"


def validate_micro_path(graph: RMicroGraph, edge_ids: Sequence[int]) -> Tuple[bool, str]:
    """Validate that edge IDs form exactly one complete ODD-to-ODD R-block path."""
    if not edge_ids:
        return False, "empty_path"
    try:
        path = [graph.edges_by_id[int(i)] for i in edge_ids]
    except (KeyError, ValueError) as exc:
        return False, f"unknown_edge:{exc}"
    if path[0].src.phase != PHASE_ODD or path[0].operation != OP_3N_PLUS_1:
        return False, "invalid_start"
    if path[-1].dst.phase != PHASE_ODD:
        return False, "invalid_end"
    for a, b in zip(path, path[1:]):
        if a.dst != b.src:
            return False, "disconnected_path"
    division_edges = path[1:]
    if not division_edges or division_edges[0].operation != OP_FIRST_DIVIDE_BY_2:
        return False, "missing_first_division"
    if any(e.operation != OP_EXTRA_DIVIDE_BY_2 for e in division_edges[1:]):
        return False, "invalid_extra_division_operation"
    if any(e.dst.phase == PHASE_ODD for e in division_edges[:-1]):
        return False, "premature_odd_boundary"
    return True, "PASS"


def lift_micro_path_to_witness(graph: RMicroGraph, edge_ids: Sequence[int]) -> int:
    """Construct a positive odd witness realizing one valid finite R-block path.

    The final odd residue is lifted by CRT modulo 3 so that
    ``2**t * final_odd == 1 (mod 3)``.  The resulting
    ``n=(2**t*final_odd-1)//3`` realizes the complete path.
    """
    ok, reason = validate_micro_path(graph, edge_ids)
    if not ok:
        raise RTransitionError(f"cannot lift invalid micro path: {reason}")
    path = [graph.edges_by_id[int(i)] for i in edge_ids]
    t = len(path) - 1
    final_residue = path[-1].dst.residue
    start_residue = path[0].src.residue

    final_odd: Optional[int] = None
    for l in range(3):
        candidate = final_residue + graph.M * l
        if candidate > 0 and ((1 << t) * candidate - 1) % 3 == 0:
            final_odd = candidate
            break
    if final_odd is None:
        # Adding 3M preserves the mod-3 condition, so failure here is impossible.
        raise AssertionError("CRT lift for final odd residue failed")
    n = ((1 << t) * final_odd - 1) // 3
    if n <= 0 or n % 2 == 0 or n % graph.M != start_residue:
        raise AssertionError("constructed witness does not satisfy source residue")
    actual = trace_witness(graph, n)
    if actual.micro_edge_ids != tuple(edge_ids):
        raise AssertionError(
            f"constructed witness follows different path: expected={tuple(edge_ids)} "
            f"actual={actual.micro_edge_ids}"
        )
    return n

I.12.22 LIC_r_transition.py

#!/usr/bin/env python3
"""Exact odd-to-odd Collatz R-transition support.

Source metadata:
    File name: LIC_r_transition.py
    Program version: X04a
    Source file version: 1.0.2
    Created: 2026-07-23 15:56:26 JST
    Last updated: 2026-08-02 16:32:00 JST

Function summary:
    Implements R(n), the total division count T(n), additional divisions, exact transition
    records, logical-edge construction, and independent transition checks using integer
    arithmetic.

Remarks:
    No floating-point arithmetic or artificial upper bound is used in the exact transition
    functions.
    Individual source-file versioning starts with this metadata revision. Earlier file-level
    changes are retained in package history but are not reconstructed as separate source-file
    versions.

Change history:
    - 1.0.2 / X04a / 2026-08-02 16:32:00 JST
      Updated X04a Program-membership metadata; executable logic is unchanged.
    - 1.0.1 / X03f / 2026-08-01 23:28:33 JST
      Updated the source metadata header for inclusion in the X03f Program package; executable logic is unchanged.
    - 1.0.0 / X03e / 2026-08-01 05:17:15 JST
      Added the standardized English source metadata header and established the
      initial individual source-file version baseline.

Detailed description:
    This module implements the mathematical transition used by Chapter 3:

        R(n) = (3*n + 1) / 2**T(n),
        T(n) = ord_2(3*n + 1),
        additional_divisions(n) = T(n) - 1.

    All arithmetic is exact integer arithmetic.  No finite upper bound is imposed
    on T(n).  The module is deliberately independent of the LP and family-removal
    layers so its contract can be tested before integration.
"""
from __future__ import annotations

from dataclasses import asdict, dataclass, replace
from typing import Dict, Iterable, Iterator, Optional, Tuple

from LIC_constants import (
    COLLATZ_INCREMENT,
    COLLATZ_MULTIPLIER,
    DEFAULT_ODD_TRANSITION_DIVISIONS,
    R_TRANSITION_MODEL_EXACT_LOGICAL_EDGE,
    R_TRANSITION_SCHEMA_VERSION,
)
from LIC_version import PACKAGE_LABEL, PACKAGE_VERSION

__program_id__ = "LIC_r_transition"
__version__ = PACKAGE_VERSION


class RTransitionError(ValueError):
    """Raised when an exact R-transition input or record is invalid."""


def _require_positive_odd_integer(n: int) -> int:
    if isinstance(n, bool) or not isinstance(n, int):
        raise RTransitionError(f"R-transition input must be an integer, got {type(n).__name__}")
    if n <= 0:
        raise RTransitionError(f"R-transition input must be positive, got {n}")
    if n % 2 == 0:
        raise RTransitionError(f"R-transition input must be odd, got {n}")
    return n


def _require_power_of_two_modulus(M: int) -> int:
    if isinstance(M, bool) or not isinstance(M, int):
        raise RTransitionError(f"modulus M must be an integer, got {type(M).__name__}")
    if M < 2 or (M & (M - 1)) != 0:
        raise RTransitionError(f"modulus M must be a power of two >= 2, got {M}")
    return M


def v2_positive(n: int) -> int:
    """Return ord_2(n) for a positive integer using exact bit arithmetic."""
    if isinstance(n, bool) or not isinstance(n, int) or n <= 0:
        raise RTransitionError(f"v2_positive expects a positive integer, got {n!r}")
    return (n & -n).bit_length() - 1


@dataclass(frozen=True)
class ExactRTransition:
    """One exact positive-odd to positive-odd Collatz transition."""

    witness: int
    next_odd: int
    t: int
    additional_divisions: int

    def as_dict(self) -> Dict[str, int]:
        return asdict(self)


@dataclass(frozen=True)
class LogicalREdge:
    """Finite-state logical edge backed by one exact positive-integer witness."""

    transition_model: str
    transition_schema_version: int
    package_label: str
    M: int
    witness: int
    src: int
    dst: int
    next_odd: int
    t: int
    additional_divisions: int

    def as_dict(self) -> Dict[str, object]:
        return asdict(self)


def exact_r_transition(n: int) -> ExactRTransition:
    """Compute the exact one-step odd Collatz transition for positive odd ``n``."""
    n = _require_positive_odd_integer(n)
    value = COLLATZ_MULTIPLIER * n + COLLATZ_INCREMENT
    t = v2_positive(value)
    next_odd = value >> t
    additional = t - DEFAULT_ODD_TRANSITION_DIVISIONS

    # Internal assertions state the mathematical contract directly.
    if next_odd <= 0 or next_odd % 2 == 0:
        raise AssertionError("exact R-transition did not end at a positive odd integer")
    if additional < 0:
        raise AssertionError("positive odd input must have at least one division by two")
    if value != (1 << t) * next_odd:
        raise AssertionError("exact R-transition factorization identity failed")

    return ExactRTransition(
        witness=n,
        next_odd=next_odd,
        t=t,
        additional_divisions=additional,
    )


def R(n: int) -> int:
    """Return the next positive odd integer in the accelerated Collatz map."""
    return exact_r_transition(n).next_odd


def T(n: int) -> int:
    """Return ord_2(3*n+1) for a positive odd integer."""
    return exact_r_transition(n).t


def additional_divisions(n: int) -> int:
    """Return T(n)-1, the Chapter 3 additional-division contribution."""
    return exact_r_transition(n).additional_divisions


def make_logical_r_edge(n: int, M: int) -> LogicalREdge:
    """Map one exact R-transition to an odd-residue logical edge modulo ``M``."""
    M = _require_power_of_two_modulus(M)
    tr = exact_r_transition(n)
    src = n % M
    dst = tr.next_odd % M
    if src == 0 or src % 2 == 0:
        raise AssertionError(f"unexpected non-odd source residue {src}")
    if dst == 0 or dst % 2 == 0:
        raise AssertionError(f"unexpected non-odd destination residue {dst}")
    return LogicalREdge(
        transition_model=R_TRANSITION_MODEL_EXACT_LOGICAL_EDGE,
        transition_schema_version=R_TRANSITION_SCHEMA_VERSION,
        package_label=PACKAGE_LABEL,
        M=M,
        witness=n,
        src=src,
        dst=dst,
        next_odd=tr.next_odd,
        t=tr.t,
        additional_divisions=tr.additional_divisions,
    )


def verify_exact_r_transition(record: ExactRTransition) -> Tuple[bool, str]:
    """Independently recompute and verify an ``ExactRTransition`` record."""
    try:
        expected = exact_r_transition(record.witness)
    except Exception as exc:  # malformed record input
        return False, f"recompute_error:{type(exc).__name__}:{exc}"
    if record != expected:
        return False, f"record_mismatch:expected={expected!r}:actual={record!r}"
    return True, "PASS"


def verify_logical_r_edge(edge: LogicalREdge) -> Tuple[bool, str]:
    """Independently recompute and verify every field of a logical R-edge."""
    try:
        expected = make_logical_r_edge(edge.witness, edge.M)
    except Exception as exc:
        return False, f"recompute_error:{type(exc).__name__}:{exc}"
    if edge != expected:
        fields = []
        for name in edge.__dataclass_fields__:
            actual_value = getattr(edge, name)
            expected_value = getattr(expected, name)
            if actual_value != expected_value:
                fields.append(f"{name}:expected={expected_value!r}:actual={actual_value!r}")
        return False, "record_mismatch:" + ";".join(fields)
    return True, "PASS"


def iter_logical_r_edges(witnesses: Iterable[int], M: int) -> Iterator[LogicalREdge]:
    """Yield exact logical R-edges for the supplied positive odd witnesses."""
    M = _require_power_of_two_modulus(M)
    for n in witnesses:
        yield make_logical_r_edge(n, M)


def corrupt_edge_for_test(edge: LogicalREdge, **changes: object) -> LogicalREdge:
    """Return a modified immutable record for negative verifier tests only."""
    return replace(edge, **changes)

I.12.23 LIC_status.py

#!/usr/bin/env python3
"""Canonical concise status values for the CTV Core package.

Source metadata:
    File name: LIC_status.py
    Program version: X04a
    Source file version: 1.0.2
    Created: 2026-07-29 23:55:10 JST
    Last updated: 2026-08-02 16:32:00 JST

Function summary:
    Defines the shared PASS, FAIL, and WARN status tokens and the immutable set of valid status
    values.

Remarks:
    Only the canonical concise status values should be used in machine-readable status fields.
    Individual source-file versioning starts with this metadata revision. Earlier file-level
    changes are retained in package history but are not reconstructed as separate source-file
    versions.

Change history:
    - 1.0.2 / X04a / 2026-08-02 16:32:00 JST
      Updated X04a Program-membership metadata; executable logic is unchanged.
    - 1.0.1 / X03f / 2026-08-01 23:28:33 JST
      Updated the source metadata header for inclusion in the X03f Program package; executable logic is unchanged.
    - 1.0.0 / X03e / 2026-08-01 05:17:15 JST
      Added the standardized English source metadata header and established the
      initial individual source-file version baseline.
"""

STATUS_PASS = "PASS"
STATUS_FAIL = "FAIL"
STATUS_WARN = "WARN"

VALID_STATUS_VALUES = frozenset({STATUS_PASS, STATUS_FAIL, STATUS_WARN})

I.12.24 LIC_structural_lambda_certificate.py

#!/usr/bin/env python3
"""Generator for the structural lambda certificate.

Source metadata:
    File name: LIC_structural_lambda_certificate.py
    Program version: X04a
    Source file version: 1.0.2
    Created: 2026-07-29 23:55:10 JST
    Last updated: 2026-08-02 16:32:00 JST

Function summary:
    Derives the structural lambda value from the independently verified complete periodic-lift
    classification and writes the Layer 2 certificate and evidence bindings.

Remarks:
    The expected structural value is used only for the final fixed-judgment comparison, not for
    candidate search or exclusion.
    Individual source-file versioning starts with this metadata revision. Earlier file-level
    changes are retained in package history but are not reconstructed as separate source-file
    versions.

Change history:
    - 1.0.2 / X04a / 2026-08-02 16:32:00 JST
      Updated X04a Program-membership metadata; executable logic is unchanged.
    - 1.0.1 / X03f / 2026-08-01 23:28:33 JST
      Updated the source metadata header for inclusion in the X03f Program package; executable logic is unchanged.
    - 1.0.0 / X03e / 2026-08-01 05:17:15 JST
      Added the standardized English source metadata header and established the
      initial individual source-file version baseline.
"""
from __future__ import annotations

import hashlib
import json
from pathlib import Path
from typing import Dict

from LIC_certificate_metadata import add_creation_metadata, certificate_digest
from LIC_complete_cycle_classification_verifier import verify_run as verify_complete_classification
from LIC_version import PACKAGE_LABEL, PACKAGE_VERSION
from LIC_status import STATUS_FAIL, STATUS_PASS

__program_id__ = "LIC_structural_lambda_certificate"
__version__ = PACKAGE_VERSION
STRUCTURAL_ID = "LIC-VALID-PERIODIC-LIFT-STRUCTURAL-LAMBDA-v2"
_SCOPE = (
    "normalized convex combinations of positive-integer periodic lifts of simple "
    "logical R-cycle extreme candidates in the exact finite R graph"
)


def _canonical(obj: object) -> bytes:
    return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")


def _digest(obj: object) -> str:
    return hashlib.sha256(_canonical(obj)).hexdigest()


def _sha(path: Path) -> str:
    h = hashlib.sha256()
    with Path(path).open("rb") as f:
        for block in iter(lambda: f.read(1 << 20), b""):
            h.update(block)
    return h.hexdigest()


def write_structural_lambda_certificate(classification_run_dir: Path, out_dir: Path) -> Dict[str, object]:
    classification_run_dir = Path(classification_run_dir)
    out_dir = Path(out_dir)
    out_dir.mkdir(parents=True, exist_ok=True)

    classification_verify_path = classification_run_dir / "complete_cycle_classification_verify_summary.json"
    if classification_verify_path.is_file():
        verified = json.loads(classification_verify_path.read_text(encoding="utf-8"))
    else:
        verified = verify_complete_classification(classification_run_dir)
    classification = json.loads(
        (classification_run_dir / "complete_cycle_classification_certificate.json").read_text(encoding="utf-8")
    )
    audit = json.loads(
        (classification_run_dir / "minimum_candidate_audit" / "cycle_minimum_candidate_audit_summary.json").read_text(encoding="utf-8")
    )
    returned = audit.get("returned_cycle_summaries")
    trivial = [{"minimum_candidate": 1, "steps": 1, "sum_T": 2, "max_value_bit_length": 1}]
    classification_ok = (
        verified.get("verification_status") == "PASS"
        and classification.get("status") == STATUS_PASS
        and returned == trivial
        and int(classification.get("nontrivial_positive_integer_periodic_lifts_found", -1)) == 0
    )

    # For the unique valid extreme structure, L=1 and T=2, hence lambda_x=(T-1)/L=1.
    L = 1
    sum_extra = 1
    structural_lambda_num = sum_extra
    structural_lambda_den = L
    structural_ok = classification_ok and structural_lambda_num == structural_lambda_den
    status = STATUS_PASS if structural_ok else STATUS_FAIL

    core: Dict[str, object] = {
        "structural_certificate_id": STRUCTURAL_ID,
        "package_label": PACKAGE_LABEL,
        "M": int(classification["M"]),
        "classification_status": classification.get("status"),
        "classification_independent_verify_status": verified.get("verification_status"),
        "valid_periodic_lift_extreme_structures": 1 if classification_ok else None,
        "valid_extreme_structure": {"minimum_candidate": 1, "length_L": 1, "sum_T": 2, "sum_additional_divisions": 1},
        "structural_lambda_x_numerator": structural_lambda_num,
        "structural_lambda_x_denominator": structural_lambda_den,
        "structural_lambda_x_exact": "1",
        "convex_hull_conclusion": (
            "Because the independently verified valid extreme-structure set contains only the trivial 1-loop, "
            "every normalized convex combination of valid periodic-lift extreme structures has lambda_x = 1."
        ),
        "certificate_scope": _SCOPE,
        "underlying_graph_edge_deletion_used": False,
        "legacy_catalog_exclusion_used": False,
        "unrestricted_infinite_empirical_flow_claimed": False,
        "classification_certificate_sha256": _sha(classification_run_dir / "complete_cycle_classification_certificate.json"),
        "classification_verify_sha256": _sha(classification_run_dir / "complete_cycle_classification_verify_summary.json"),
        "minimum_audit_summary_sha256": _sha(classification_run_dir / "minimum_candidate_audit" / "cycle_minimum_candidate_audit_summary.json"),
        "status": status,
    }
    add_creation_metadata(core, __program_id__)
    core["structural_certificate_sha256"] = certificate_digest(core, "structural_certificate_sha256")
    cert_path = out_dir / "structural_lambda_certificate.json"
    cert_path.write_text(json.dumps(core, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    report = [
        f"# Structural lambda certificate — M={core['M']}", "",
        f"- package: `{PACKAGE_LABEL}`",
        f"- status: **{status}**",
        "- valid positive-integer periodic-lift extreme structures: `1`",
        "- unique structure: trivial `1 -> 1`, ordered T-pattern `(2)`",
        "- exact structural value: `lambda_x = 1`",
        "- underlying graph edge deletion used: `false`",
        "- legacy catalog exclusion used: `false`",
        "- unrestricted infinite empirical-flow claim: `false`",
    ]
    (out_dir / "structural_lambda_report.md").write_text("\n".join(report) + "\n", encoding="utf-8")
    return core

I.12.25 LIC_structural_lambda_certificate_verifier.py

#!/usr/bin/env python3
"""Independent verifier for the structural lambda certificate.

Source metadata:
    File name: LIC_structural_lambda_certificate_verifier.py
    Program version: X04a
    Source file version: 2.0.0
    Created: 2026-07-29 23:57:06 JST
    Last updated: 2026-08-02 16:32:00 JST

Function summary:
    Reconstructs the structural-value set from verified Layer 1 evidence, checks the exact value
    and fixed judgment, validates metadata and digests, and records the Layer 2 result.

Remarks:
    The verifier distinguishes Fixed, NOT_FIXED, and UNVERIFIED according to evidence and
    reconstruction results.
    Individual source-file versioning starts with this metadata revision. Earlier file-level
    changes are retained in package history but are not reconstructed as separate source-file
    versions.

Change history:
    - 2.0.0 / X04a / 2026-08-02 16:32:00 JST
      Reconstructed the Layer 2 structural-value set through the independent Chapter 3 mathematical layer.
    - 1.1.1 / X04a / 2026-08-02 16:32:00 JST
      Updated X04a Program-membership metadata; executable logic is unchanged.
    - 1.1.0 / X03f / 2026-08-01 23:33:00 JST
      Added author-identity consistency verification across the structural, classification, and audit certificates.
    - 1.0.1 / X03f / 2026-08-01 23:28:33 JST
      Updated the source metadata header for inclusion in the X03f Program package; executable logic is unchanged.
    - 1.0.0 / X03e / 2026-08-01 05:17:15 JST
      Added the standardized English source metadata header and established the
      initial individual source-file version baseline.
"""
from __future__ import annotations

import hashlib
import json
from pathlib import Path
from typing import Dict

from LIC_certificate_metadata import certificate_digest, finalize_certificate, metadata_checks, verification_record
from LIC_complete_cycle_classification_verifier import verify_run as verify_complete_classification
from LIC_independent_ch3_math import reconstruct_structural_values
from LIC_version import PACKAGE_LABEL, PACKAGE_VERSION
from LIC_status import STATUS_FAIL, STATUS_PASS

__program_id__ = "LIC_structural_lambda_certificate_verifier"
__version__ = PACKAGE_VERSION
_SCOPE = (
    "normalized convex combinations of positive-integer periodic lifts of simple "
    "logical R-cycle extreme candidates in the exact finite R graph"
)


def _canonical(obj: object) -> bytes:
    return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")


def _digest(obj: object) -> str:
    return hashlib.sha256(_canonical(obj)).hexdigest()


def _sha(path: Path) -> str:
    h = hashlib.sha256()
    with Path(path).open("rb") as f:
        for block in iter(lambda: f.read(1 << 20), b""):
            h.update(block)
    return h.hexdigest()


def verify_run(run_dir: Path, classification_run_dir: Path | None = None) -> Dict[str, object]:
    run_dir = Path(run_dir)
    classification_run_dir = Path(classification_run_dir) if classification_run_dir is not None else run_dir.parent / "periodic_lift_classification"
    cert_path = run_dir / "structural_lambda_certificate.json"
    cert = json.loads(cert_path.read_text(encoding="utf-8"))
    classification_verify_path = classification_run_dir / "complete_cycle_classification_verify_summary.json"
    if classification_verify_path.is_file():
        cv = json.loads(classification_verify_path.read_text(encoding="utf-8"))
    else:
        cv = verify_complete_classification(classification_run_dir)
    classification = json.loads((classification_run_dir / "complete_cycle_classification_certificate.json").read_text(encoding="utf-8"))
    audit = json.loads((classification_run_dir / "minimum_candidate_audit" / "cycle_minimum_candidate_audit_summary.json").read_text(encoding="utf-8"))
    expected_trivial = [{"minimum_candidate": 1, "steps": 1, "sum_T": 2, "max_value_bit_length": 1}]
    returned_cycles = audit.get("returned_cycle_summaries")
    reconstructed_values = reconstruct_structural_values(returned_cycles) if isinstance(returned_cycles, list) else []
    checks = {
        **metadata_checks(cert, "LIC_structural_lambda_certificate"),
        "package_label_ok": cert.get("package_label") == PACKAGE_LABEL,
        "input_certificate_author_ids_match": (
            cert.get("certificate_author_id")
            == classification.get("certificate_author_id")
            == audit.get("certificate_author_id")
        ),
        "id_ok": cert.get("structural_certificate_id") == "LIC-VALID-PERIODIC-LIFT-STRUCTURAL-LAMBDA-v2",
        "digest_ok": cert.get("structural_certificate_sha256") == certificate_digest(cert, "structural_certificate_sha256"),
        "classification_verify_pass": cv.get("verification_status") == "PASS",
        "classification_status_ok": classification.get("status") == STATUS_PASS,
        "M_ok": int(cert.get("M", -1)) == int(classification.get("M", -2)),
        "trivial_only_reconstructed": audit.get("returned_cycle_summaries") == expected_trivial and int(audit.get("nontrivial_return_count", -1)) == 0,
        "valid_extreme_count_ok": int(cert.get("valid_periodic_lift_extreme_structures", -1)) == len(returned_cycles or []) == 1,
        "lambda_exact_ok": (
            reconstructed_values == ["1"]
            and int(cert.get("structural_lambda_x_numerator", -1)) == 1
            and int(cert.get("structural_lambda_x_denominator", -1)) == 1
            and cert.get("structural_lambda_x_exact") == "1"
        ),
        "scope_ok": cert.get("certificate_scope") == _SCOPE,
        "no_edge_deletion_ok": cert.get("underlying_graph_edge_deletion_used") is False and cert.get("legacy_catalog_exclusion_used") is False,
        "no_unrestricted_flow_claim_ok": cert.get("unrestricted_infinite_empirical_flow_claimed") is False,
        "input_hashes_ok": cert.get("classification_certificate_sha256") == _sha(classification_run_dir / "complete_cycle_classification_certificate.json") and cert.get("classification_verify_sha256") == _sha(classification_run_dir / "complete_cycle_classification_verify_summary.json") and cert.get("minimum_audit_summary_sha256") == _sha(classification_run_dir / "minimum_candidate_audit" / "cycle_minimum_candidate_audit_summary.json"),
        "status_ok": cert.get("status") == STATUS_PASS,
    }
    ok = all(checks.values())
    status = STATUS_PASS if ok else STATUS_FAIL
    cert = finalize_certificate(cert_path, cert, verifier_program_id=__program_id__, verification_status=status, digest_field="structural_certificate_sha256")
    result = {
        "package_label": PACKAGE_LABEL,
        "M": cert.get("M"),
        "verification_status": status,
        "overall_status": STATUS_PASS if ok else STATUS_FAIL,
        "checks": checks,
        **verification_record(cert),
        "independent_mathematical_reconstruction_program_id": "LIC_independent_ch3_math",
        "reconstructed_structural_lambda_x_values": reconstructed_values,
        "verified_certificate_sha256": _sha(cert_path),
    }
    (run_dir / "structural_lambda_verify_summary.json").write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    return result

I.12.26 LIC_version.py

#!/usr/bin/env python3
"""Version constants for the separated Appendix-I CTV Core package.

Source metadata:
    File name: LIC_version.py
    Program version: X04a
    Source file version: 1.2.0
    Created: 2026-07-29 23:55:10 JST
    Last updated: 2026-08-02 16:32:00 JST

Function summary:
    Defines the current Program version, document-combination label, package label, parent
    package, and retained compatibility identifiers used throughout the Core workflow.

Remarks:
    Program versioning is separate from each source file version. Updating this module does not
    by itself authorize changes to official paper documents.
    Individual source-file versioning starts with this metadata revision. Earlier file-level
    changes are retained in package history but are not reconstructed as separate source-file
    versions.

Change history:
    - 1.2.0 / X04a / 2026-08-02 16:32:00 JST
      Updated the Program candidate version to X04a and set X03f-D01 as the retained parent package.
    - 1.1.0 / X03f / 2026-08-01 23:28:33 JST
      Updated the Program version to X03f for the configurable certificate-author identity revision.
    - 1.0.0 / X03e / 2026-08-01 05:17:15 JST
      Added the standardized English source metadata header and established the
      initial individual source-file version baseline.
"""
PROGRAM_VERSION = "X04a"
DOCUMENT_VERSION = "D01"
PACKAGE_LABEL = f"{PROGRAM_VERSION}-{DOCUMENT_VERSION}"
PACKAGE_VERSION = PROGRAM_VERSION

BASE_STANDARD_VERSION = "v30"
DEFAULT_PREPRUNE_CATALOG_NAME = "LIC_forbidden_pattern_catalog_accepted.csv"
PARENT_PACKAGE = "X03f-D01"
PACKAGE_ROLE = "all-supported-M-two-layer-core-certificate-with-independent-mathematical-reconstruction"

////////////////////////////////////////////////////////////////////
 上記の付録I に対応する本文側の記述を以下に示す。
ただし、これらの内容は、あくまで参考記述であり、正式な本文ではない。


  第 3 章 有限状態 LP と有限検査証明
    3.1 有限状態 LP の基本概念
      3.1.1 奇数コラッツ遷移と追加除算回数
      3.1.2 exact R-micrograph と derived logical R-graph
      3.1.3 LP 実数緩和と closed circulation
      3.1.4 micrograph path、closed-walk と循環経路の区別
      3.1.5 closed-walk パターンと family
    3.2 有限状態 LP の定式化
      3.2.1 有限 logical edge 集合と辺ラベル
      3.2.2 LP 実数緩和可行領域
      3.2.3 closed-walk flow と closed circulation の分解
      3.2.4 周期 lift を持つ extreme structure と有効 LP 可行解
    3.3 正整数周期 lift の必要条件
      3.3.1 ordered T-pattern の合成写像と周期閉包
      3.3.2 正整数循環経路の平均追加除算回数比率
      3.3.3 cycle 長毎の周期最小値上界
      3.3.4 finite circulation simple extreme-cycle 全長の有限還元
    3.4 周期最小値候補の完全有限監査
      3.4.1 exact R-micrograph、derived logical R-graph と検査単位
      3.4.2 全奇数最小値候補監査
      3.4.3 完全有限監査による周期 lift 分類
    3.5 2層 core certificate
      3.5.1 証明書の論理構成
      3.5.2 正式採用法における確認結果
      3.5.3 本証明書の適用範囲
    3.6 有効 LP 可行解構造定理
    3.7 有限状態 mapping における軌道情報保存
    3.8 有限状態構造分類の循環経路への適用

第 3 章 有限状態 LP と有限検査証明

 本章では、奇数コラッツ遷移を、有限個の内部状態からなる
exact $R$-micrograph へ射影し、そこから simple extreme-cycle 候補の
列挙に用いる有限な derived logical $R$-graph を構成する。その上で、
derived logical $R$-graph 上の LP 実数緩和可行領域を定式化する。

 exact $R$-micrograph は、任意の正の奇数に対する一回の
完全な $R()$ 遷移を、有限状態上の有限辺列として表す。
ただし、除算回数は正整数全体で上に有界でないため、
一般の $R()$ 遷移に対応する micrograph path は、
内部状態を重複通過する場合がある。
 一方、derived logical $R$-graph は、全ての実 $R()$ 遷移を
一辺ずつ収容するグラフではなく、有限状態 LP の
simple extreme-cycle 候補を有限個に列挙するためのグラフである。
 derived logical $R$-graph の一つの logical edge は、
micrograph 上の内部状態を重複しない、一回の完全な
ODD-to-ODD path だけを集約したものである。

 本章の理論的出発点はコラッツ遷移一般方程式である。
これに周期閉包条件を課すと、循環経路が満たす平均追加除算回数比率の
必要範囲が得られる。
 さらに、その必要範囲から周期最小値の有限上界を導き、
derived logical $R$-graph の全 simple extreme-cycle 候補に対する
正整数周期 lift の可能性を、有限個の正整数最小値候補へ還元する。

 付録I の検証プログラムは、
exact $R$-micrograph、derived logical $R$-graph、両者の対応および
有限状態 extreme-cycle bridge を独立に確認する。
 さらに、上界以下の全奇数候補を $R()$ により直接監査し、
正整数周期軌道へ lift 可能な simple extreme-cycle 候補が、
奇数状態 $1$ の自明なループに由来するものだけであることを確認する。
その結果と独立検証記録を2層の core certificate に束縛する。

 なお、本章では、derived logical $R$-graph 上の線形制約によって定まる
LP可行領域、LP可行解およびそのextreme-point構造を数学的に利用する。
ただし、付録I の検証プログラムは、SciPy linprog、HiGHS その他の
LP solver を起動せず、線形計画問題を数値的に求解しない。

 本章の最終的な目的は、core certificate の Layer 1 による
正整数周期 lift の完全分類を根拠として、有効 LP 可行解構造定理を
示すことである。
 すなわち、正整数周期 lift を持つ有効な extreme structure は
自明なループに由来するものに限られ、その正規化凸結合からなる
任意の有効 LP 可行解について、平均追加除算回数は恒等的に $1$ となる。
 したがって、構造下界値は、

\lambda_x^{\mathrm{str}} = 1.

となる。
 Layer 2 は、この導出結果を独立に再構成して確認する証拠層であり、
本章の構造定理における数学的前提そのものではない。

 本章は、非自明循環経路の存在排除そのものを結論しない。
本章が直接分類する対象は、
derived logical $R$-graph の simple extreme-cycle 候補の内、
正整数周期軌道へ lift 可能な構造である。

3.1 有限状態 LP の基本概念

 本節では、奇数コラッツ遷移から有限状態 LP を構成するまでの
基本概念を導入する。
 特に、LP 実数緩和上の closed-walk および closed circulation と、
コラッツ遷移上の循環経路を区別する。

3.1.1 奇数コラッツ遷移と追加除算回数

 定義1.1.7 で定義した $R(n)$ は、
任意の正の奇数 $n$ から次の奇数への一段の奇数コラッツ遷移を表す。
すなわち、

R(n) = \frac{3n + 1}{2^{\operatorname{ord}_2(3n + 1)}}.

 正の奇数 $V_0$ から始まる奇数コラッツ遷移列を、

V_i = R(V_{i - 1}) \qquad (i = 1, 2, \ldots, n).

とする。第 $i$ 段における $2$ による除算回数を、

T_i := \operatorname{ord}_2 \left( 3V_{i - 1} + 1 \right).

と書く。このとき、

V_i = \frac{3V_{i - 1} + 1}{2^{T_i}}.

である。

 一段の奇数コラッツ遷移では、$3V_{i - 1} + 1$ が偶数であるため、
$2$ による除算が少なくとも $1$ 回は必ず発生する。
この必ず発生する $1$ 回分を除いた第 $i$ 段の追加除算寄与を、

a_i := T_i - 1.

と書く。

 除算総回数は、

S_n = \sum_{i = 1}^{n} T_i.

である。追加除算回数の総和 $x_n$ は、

\begin{aligned}
x_n
& :=
\sum_{i = 1}^{n} a_i\\
& =
\sum_{i = 1}^{n}
\left(
T_i - 1
\right)\\
& =
S_n - n.
\end{aligned}.

と書ける。したがって、本章においても、$x_n$ は常に第 $n$ 段までの
追加除算回数の総和を意味し、一段毎の量を表す記号ではない。

3.1.2 exact R-micrograph と derived logical R-graph

 $b \in \mathbb{Z}_{\ge 2}$ に対して、法 $M = 2^b$ を固定する。
正の奇数 $n$ の法 $M$ による奇数剰余状態を

\rho_M(n) \in S_M.

と書く。ここで、$S_M$ は $M/2$ 個の奇数剰余状態からなる。

 任意の一回の完全な奇数コラッツ遷移 $n \mapsto R(n)$ を有限状態上で
段階的に表すため、次の3種類の phase を持つ microstate を導入する。

ODD_BOUNDARY
AFTER_3N_PLUS_1
DIVISION_CONTINUE

 各 microstate は、phase と法 $M$ による剰余の組である。
ODD_BOUNDARY では奇数剰余を用い、他の二つの phase では
偶数剰余を用いる。この有限 microstate 集合を $\widetilde{S}_M$ と書く。
その状態数は、

\left| \widetilde{S}_M \right| = \frac{3M}{2}.

である。

 microedge は、次の3種類の操作のいずれかを表す。

APPLY_3N_PLUS_1
FIRST_DIVIDE_BY_2
EXTRA_DIVIDE_BY_2

 ODD_BOUNDARY の奇数剰余 $r$ からは、$(3r+1) \bmod M$ へ
APPLY_3N_PLUS_1を一回適用する。
 偶数剰余 $r$ を $2$ で除算した後の剰余は、

\frac{r}{2}
\quad \text{or} \quad
\frac{r}{2} + \frac{M}{2}
\pmod{M}.

のいずれかである。実際、偶数整数 $x=r+kM$ に対して、

\frac{x}{2} = \frac{r}{2} + k \frac{M}{2}.

であり、$k$ の偶奇により上記二つの剰余が得られる。
したがって、各除算 microedge は、この二つの可能な剰余遷移を持つ。
 この有限有向グラフを exact $R$-micrograph と呼び、
その microedge 集合を

\widetilde{E}_M.

と書く。

 実際の正の奇数 $n$ に対して、$3n + 1$ を適用し、奇数になるまで
$2$ で除算する各段階を法 $M$ へ射影すると、ODD_BOUNDARY から次の
ODD_BOUNDARY までの有限 micrograph path が一意に得られる。
 したがって、任意の実 $R()$ 遷移は、exact $R$-micrograph 上の
有限辺列として正確に追跡される。

 ただし、$\operatorname{ord}_2(3n + 1)$ は正整数全体で上に有界でない。
したがって、一般の実 $R()$ 遷移に対応する micrograph path は、
同一の内部 microstate を重複通過する場合があり、必ずしも
一つの有限 logical edge として表されるわけではない。

 そこで本章では、exact $R$-micrograph 上の一回の完全な
ODD-to-ODD path のうち、内部 microstate を重複通過しないものだけを
一つの logical edge へ集約する。
 この有限個の logical edge からなるグラフを
derived logical $R$-graph と呼ぶ。
その正式な辺集合および辺ラベルは §3.2.1 で定義する。

 derived logical $R$-graph の目的は、全ての実 $R()$ 遷移を一辺ずつ
一対一に保存することではない。
 有限状態 LP の simple extreme-cycle 候補を有限個の構造へ還元し、
そのうち正整数周期軌道へ lift 可能なものを判定することにある。

3.1.3 LP 実数緩和と closed circulation

 用語集で定義した LP を、本章では、§3.2.1で定義する
finite derived logical $R$-graph の各 logical edge $e$ に
非負実数重み $q_e$ を割り当てる形で用いる。
 各奇数剰余状態において流入重みと流出重みが等しいという
線形制約を課し、さらに全logical edge重みの総和を $1$ に正規化する。

 本稿における LP 実数緩和は、コラッツ遷移値そのものを非整数値へ
拡張するものではない。
 finite logical edge の通過頻度を、各辺への非負実数重みの割当てとして
扱うものである。
 したがって、LP 可行解は個々の整数軌道そのものではなく、
derived logical $R$-graph 上の実数重み付きフローである。

 derived logical $R$-graph の各辺に非負実数重みを割り当て、
各奇数剰余状態において流入重みの総和と流出重みの総和が一致する
閉じたフローをclosed circulation と呼ぶ。
 したがって、本章の LP 可行流量は、derived logical $R$-graph 上の
closed circulation である。
 closed circulation は、一本の有限長遷移列または
一つの実整数軌道そのものではない。

3.1.4 micrograph path、closed-walk と循環経路の区別

 exact $R$-micrograph 上の micrograph path は、$3n + 1$ および
その後の各 $2$ 除算を有限状態上で段階的に表す有向辺列である。
任意の実 $R()$ 遷移は一つの有限 micrograph path を持つが、
その path は内部状態を重複通過する場合がある。

 closed-walk とは、derived logical $R$-graph 上で、
始点と終点が一致する有限長の logical edge 列をいう。
closed-walkでは、途中の状態または辺の重複を許す。
 したがって、closed-walk は simple directed cycle とは区別される。

 また、本章の closed-walk は有限状態射影上の概念である。
finite logical graph 上で始点と終点が一致していても、それだけでは、
正整数を順次通過して出発整数へ戻る循環経路を意味しない。
 各 logical edge は一つの exact ODD-to-ODD micropath を表すが、
複数 edge を連結した closed-walk 全体が、同一の正整数から出発する
一つの整数軌道として同時に実現されるか否かは、別途、
正整数周期 lift 条件によって判定する。

 closed circulation は実数重み付きの閉じたフローであり、closed-walk は
有限長の logical edge 列である。この意味で、両者は同一ではない。
 ただし、有限有向グラフ上の非零 closed circulation は、
非零重みを持つ辺の集合上で、有限個の directed-cycle flow へ分解できる。

 したがって、本章では、次の4つを区別する。
  (1) 任意の実 $R()$ 遷移を段階的に表す exact micrograph path。
  (2) derived logical $R$-graph 上の実数重み付きフローである
    closed circulation。
  (3) derived logical $R$-graph 上で閉じた有限 logical edge 列である
    closed-walk。
  (4) 正の奇数整数を順次通過して出発整数へ戻る循環経路。

 closed circulation の cycle 分解は LP 側の構造分解であり、
各 cycle が正整数コラッツ遷移として成立するか否かは、別途、
正整数周期 lift 条件によって判定する。

3.1.5 closed-walk パターンと family

 closed-walk を辺の順序に従って一周したときの除算回数列を
ordered $T$-pattern と呼ぶ。
 同一の closed-walk は、出発位置の選び方によって、
除算指数列の巡回回転として複数通りに表される。
 本章では、巡回回転によって一致する ordered $T$-pattern を同一視し、
その同値類を closed-walk family と呼ぶ。
 また、各 family から一定の規則により選ぶ代表元を
canonical $T$-pattern と呼ぶ。

 closed-walk パターンが、ある正の奇数整数から出発し、
各段階で指定された除算指数を満たしながら正の奇数整数を順次通過し、
最後に出発整数へ戻るとき、そのパターンを整数点通過可能と呼ぶ。
 また、そのような正整数のみの閉路として実現できないパターンを
非整数点通過パターンと呼ぶ。
 実際の判定条件は §3.3 で定義する。

3.2 有限状態 LP の定式化

3.2.1 有限 logical edge 集合と辺ラベル

 exact $R$-micrograph 上の一回の完全な ODD-to-ODD path を、

P = (\widetilde e_0, \widetilde e_1, \ldots, \widetilde e_t).

とする。ここで、$\widetilde e_0$ は APPLY_3N_PLUS_1、
$\widetilde e_1$ は FIRST_DIVIDE_BY_2、$\widetilde e_2$ 以降は
EXTRA_DIVIDE_BY_2 を表し、$t \ge 1$ は $2$ による除算回数である。

 本章で一つの logical edge へ集約する path $P$ は、
次の全条件を満たすものとする。
  (1) $P$ は ODD_BOUNDARY から開始する。

  (2) 最初の microedge は APPLY_3N_PLUS_1 であり、
    その後に少なくとも一回の除算 microedge が続く。

  (3) 最後の到達状態だけが次の ODD_BOUNDARY であり、
    途中で ODD_BOUNDARY を通過しない。

  (4) 始点と終点が一致する場合のその一回の一致を除き、
    path 中の microstate を重複通過しない。
    特に、内部 microstate は重複しない。

 このような path $P$ を一つの logical edge $e(P)$ へ集約する。
有限状態間の logical edge 集合を、

E_M^{\mathrm{raw}}.

と書く。
 exact $R$-micrograph は有限であり、logical edge を構成する path は
内部状態を重複しないため、$E_M^{\mathrm{raw}}$ は有限集合である。

 各 $e = e(P) \in E_M^{\mathrm{raw}}$ に対して、始点、終点、除算回数ラベル、
および元の microedge 列を、

\operatorname{src}(e), \qquad
\operatorname{dst}(e), \qquad
t_E(e), \qquad
\operatorname{micro}(e).

と書く。ここで、

\begin{aligned}
t_E(e(P)) &:= t, \\
a_E(e(P)) &:= t_E(e(P)) - 1.
\end{aligned}

と定める。$a_E(e)$ は一つの logical edge に付された一段分の
追加除算寄与ラベルであり、追加除算回数の総和 $x_n$ とは区別する。

 各 logical edge は、micrograph 上の一回の完全な ODD-to-ODD path を
そのまま保持するため、その辺ラベル $t_E(e)$ は当該 path の
厳密な除算回数に一致する。
 付録I は、各 logical edge の microedge 列、除算回数、始点・終点
および graph hash を独立に再構成して確認する。

 ただし、一般の実奇数コラッツ遷移

n\mapsto R(n).

の micrograph trace が内部状態を重複する場合、その一回の遷移は
$E_M^{\mathrm{raw}}$ の一辺としては表されない。この場合も、実遷移自体は
exact $R$-micrograph 上の有限辺列として正確に追跡される。
 したがって、$E_M^{\mathrm{raw}}$ の有限性は $\operatorname{ord}_2(3n + 1)$ 全体が
有界であることを意味しない。

 実際の奇数コラッツ遷移列が derived logical $R$-graph の辺列として
実現される場合、その各 logical edge を

e_i \qquad (i = 1, 2, \ldots, n).

と書けば、

\begin{aligned}
t_E(e_i) &= T_i, \\
a_E(e_i) &= a_i
\end{aligned}.

である。したがって、

x_n = \sum_{i = 1}^{n}a_i = \sum_{i = 1}^{n}a_E(e_i).

が成り立つ。

3.2.2 LP 実数緩和可行領域

 有限遷移集合 $E_M^{\mathrm{raw}}$ の各辺 $e$ に、非負実数重み $q_e$ を割り当てる。
有限状態フロー

q = (q_e)_{e \in E_M^{\mathrm{raw}}}.

が LP 可行流量であるとは、

\begin{aligned}
q_e & \ge 0
\qquad (e \in E_M^{\mathrm{raw}}), \\
\sum_{e \in E_M^{\mathrm{raw}}} q_e & = 1, \\
\sum_{\operatorname{src}(e) = s} q_e
& =
\sum_{\operatorname{dst}(e) = s} q_e
\qquad (s \in S_M)
\end{aligned}.

を満たすことをいう。

 この LP 実数緩和可行領域を

\mathcal{Q}_M^{\mathrm{raw}} :=
\left\{
q \in \mathbb{R}_{\ge 0}^{E_M^{\mathrm{raw}}}
\ \middle |\
\begin{aligned}
&\sum_{e \in E_M^{\mathrm{raw}}} q_e = 1, \\
&\sum_{\operatorname{src}(e) = s} q_e
= \sum_{\operatorname{dst}(e) = s} q_e \quad (\forall s \in S_M)
\end{aligned}
\right\}.

と書く。

 各 $q \in \mathcal{Q}_M^{\mathrm{raw}}$ に対する追加除算回数の平均を

\Lambda_x(q) := \sum_{e \in E_M^{\mathrm{raw}}} q_e a_E(e).

と定義する。ここで、下付き記号 $x$ は、追加除算回数の総和 $x_n$ の
一遷移当たり平均を表すことを示す。

 LP 可行流量 $q$ に対し、正の重みを持つ辺の集合

\operatorname{supp}(q) := \{e \in E_M^{\mathrm{raw}} \mid q_e \gt 0\}.

を、その support と呼ぶ。

3.2.3 closed-walk flow と closed circulation の分解

 有限状態グラフ上の closed-walk

W = (e_1, e_2, \ldots, e_L).

に対し、その正規化辺通過頻度を、

q_e^W := \frac{\#\{i \mid e_i = e\}}{L} \qquad (e \in E_M^{\mathrm{raw}}).

と定める。この $q^W = (q_e^W)$ を、$W$ に対応する正規化 closed-walk flow と呼ぶ。$q^W$ は非負性、正規化条件、および流量保存条件を満たすため、

q^W \in \mathcal{Q}_M^{\mathrm{raw}}.

である。

 $W$ の各辺 $e_i$ に付された除算回数を、

T_i := t_E(e_i).

と書き、一段ごとの追加除算寄与を、

a_i := T_i - 1.

と書く。また、長さ $L$ の closed-walk に沿う累積追加除算回数を

x_L := \sum_{i = 1}^{L} a_i.

と書く。このとき、

\begin{aligned}
\Lambda_x \left( q^W \right)
& = \frac{1}{L} \sum_{i = 1}^{L} a_E(e_i) \\
& = \frac{1}{L} \sum_{i = 1}^{L} a_i \\
& = \frac{x_L}{L}.
\end{aligned}.

が成り立つ。したがって、$\Lambda_x(q^W)$ は、closed-walk $W$ に沿う
累積追加除算回数 $x_L$ の一遷移当たり平均に一致する。

補題3.2.1 (LP 可行流量の closed-walk 分解). ◎💥
 任意の $q \in \mathcal{Q}_M^{\mathrm{raw}}$ は、有限状態グラフ上の
有限個の正規化 closed-walk flow の非負凸結合として表される。

証明.
 任意の $q \in \mathcal{Q}_M^{\mathrm{raw}}$ を固定する。正規化条件より、

\sum_{e \in E_M^{\mathrm{raw}}} q_e = 1.

であるから、$q_e \gt 0$ を満たす辺 $e$ が少なくとも一つ存在する。

 $q$ の正の流量を持つ辺を一つ選び、その辺の終点から、
正の流量を持つ出辺を順に選択する。
実際、ある状態 $s$ へ正の流量を持つ辺が流入しているならば、

\sum_{\operatorname{dst}(e) = s} q_e \gt 0.

である。$q$ は流量保存条件を満たすため、

\sum_{\operatorname{src}(e) = s} q_e = \sum_{\operatorname{dst}(e) = s} q_e \gt 0.

が成り立つ。
 したがって、状態 $s$ から出る辺の内、少なくとも一つは正の流量を持つ。
よって、順に、正の流量を持つ辺だけを選択して、順に辿ることができる。

 有限状態グラフの状態数は有限であるから、この操作を続けると、
いずれ以前に通過した状態へ再び到達する。
 最初に同一状態へ戻るまでの反復区間を取り出せば、
正の流量を持つ辺だけからなる simple directed cycle $C$ が得られる。

 $C$ の各辺を一回ずつ通過する辺指示流量を $\chi^C$ とし、

\chi_e^C := \begin{cases}
1, & e \in C, \\
0, & e \notin C.
\end{cases}

と定める。また、

\delta_C := \min_{e \in C} q_e.

と定める。$C$ のすべての辺は正の流量を持つため、

\delta_C \gt 0.

である。

 ここで、

q' := q - \delta_C \chi^C.

と定める。各 $e \in C$ について $\delta_C \le q_e$ であるから、$q'$ は非負性を保つ。
 また、$C$ は directed cycle であり、各状態における $\chi^C$ の流入量と
流出量は一致するため、$q'$ も流量保存条件を満たす。

 さらに、$\delta_C$ は $C$ 上の流量の最小値であるから、
$C$ に属する少なくとも一つの辺 $e$ について、

q'_e = 0.

となる。したがって、この操作によって正の流量を持つ辺の個数は
少なくとも一つ減少する。

 同じ操作を残余流量に対して反復する。
有限状態グラフの辺数は有限であり、各操作で正の流量を持つ辺の個数が
減少するため、この操作は有限回で終了する。
 よって、有限個の simple directed cycle

C_1, C_2, \ldots, C_r.

および正数

\delta_1, \delta_2, \ldots, \delta_r.

が存在して、

q = \sum_{j = 1}^{r} \delta_j \chi^{C_j}.

と表される。

 各 $C_j$ の長さを $L_j$ とする。$C_j$ に対応する正規化 closed-walk flow は、

q^{C_j} = \frac{1}{L_j} \chi^{C_j}.

である。ここで、

\alpha_j := \delta_j L_j \qquad (j = 1, 2, \ldots, r).

と定めれば、

\alpha_j \ge 0.

であり、

q = \sum_{j = 1}^{r} \alpha_j q^{C_j}.

と書ける。

 また、各 $q^{C_j}$ は全辺流量の総和が $1$ であるため、

\begin{aligned}
1
&=
\sum_{e \in E_M^{\mathrm{raw}}} q_e \\
&=
\sum_{e \in E_M^{\mathrm{raw}}}
\sum_{j = 1}^{r}
\alpha_j q_e^{C_j} \\
&= \sum_{j = 1}^{r} \alpha_j \sum_{e \in E_M^{\mathrm{raw}}} q_e^{C_j} \\
&= \sum_{j = 1}^{r} \alpha_j.
\end{aligned}

が成り立つ。

 したがって、$q$ は、有限個の正規化 simple directed-cycle flow の
非負凸結合として表される。特に、simple directed cycle は
closed-walk の一種であるから、$q$ は、有限個の正規化
closed-walk flow の非負凸結合として表される。

 したがって、命題は成り立つ。
$\square$

3.2.4 周期 lift を持つ extreme structure と有効 LP 可行解

 有限状態グラフ上の simple directed cycle $C$ が、正の奇数整数列

n_0, n_1, \ldots, n_L = n_0.

によって実現され、各段階で

n_i = R(n_{i - 1}) \qquad (i = 1, 2, \ldots, L).

が成立し、その有限状態射影が $C$ の論理辺列と一致するとき、
$C$ は正整数周期 lift を持つという。

 正整数周期 lift を持つ simple directed cycle 全体を

\mathcal{C}_M^{\mathrm{lift}}.

と書く。
$C \in \mathcal{C}_M^{\mathrm{lift}}$ に対応する正規化 cycle flow を $q^C$ と書く。

 本章における有効 LP 可行解全体を、

\mathcal{Q}_M^{\mathrm{eff}} := \operatorname{conv}
\left\{
q^C
\ \middle |\
C \in \mathcal{C}_M^{\mathrm{lift}}
\right\}.

と定義する。
 すなわち、本章の有効性は、有限状態 LP の任意の raw closed-walk に
無条件で与える属性ではなく、正整数周期軌道へ lift 可能であることが
確認された extreme structure と、その正規化凸結合に対して定義する。

 有効 LP 可行解に対する平均追加除算回数の構造下界値を、

\lambda_x^{\mathrm{str}} := \inf_{q \in \mathcal{Q}_M^{\mathrm{eff}}} \Lambda_x(q).

と定義する。

3.3 正整数周期 lift の必要条件

3.3.1 ordered T-pattern の合成写像と周期閉包

 長さ $L$ の ordered $T$-pattern を、

T = (T_1, T_2, \ldots, T_L).

とする。部分和を、

S_0 := 0, \qquad S_i := \sum_{r = 1}^{i} T_r \quad (i = 1, 2, \ldots, L).

と定め、

S := S_L = \sum_{i = 1}^{L} T_i.

と書く。

 コラッツ遷移一般方程式より、$L$ 段の形式的合成写像は、

F_T(n) = \frac{3^L n + C(T)}{2^S}.

である。ここで、

C(T) := \sum_{j = 0}^{L - 1} 3^{L - 1 - j} 2^{S_j}.

である。

 パターン $T$ が出発整数 $n$ へ戻るためには、

F_T(n) = n.

でなければならない。したがって、

\left( 2^S - 3^L \right) n = C(T).

であり、固定点候補は、

n_T = \frac{C(T)}{2^S - 3^L}.

である。

 ただし、$n_T$ が正の奇数整数であることだけでは十分ではない。
各段階で、

\begin{aligned}
n_i
& =
\frac{3n_{i - 1} + 1}{2^{T_i}}, \\
\operatorname{ord}_2(3n_{i - 1} + 1)
&= T_i
\qquad (i = 1, 2, \ldots, L), \\
n_L &= n_0.
\end{aligned}

が成立する必要がある。

3.3.2 正整数循環経路の平均追加除算回数比率

 正整数周期軌道に沿う平均追加除算回数比率を、

\lambda_x := \frac{1}{L} \sum_{i = 1}^{L} (T_i - 1) = \frac{S}{L} - 1.

と定義する。

定理3.3.1 (循環経路の平均追加除算回数比率の必要条件). ◎💥
 自然数の奇数からなる循環経路

V_0, V_1, \ldots, V_{L - 1}, V_L = V_0 \qquad (L \ge 1).

が存在するとする。このとき、

\alphastar \lt \lambda_x \le 1.

が成り立つ。
 また、$\lambda_x = 1$ が成立するのは、
奇数表示における自明なループ $1 \mapsto 1$ の場合に限る。

証明.
 各段階について、

2^{T_i} V_i = 3V_{i - 1} + 1 \qquad (i = 1, 2, \ldots, L).

が成り立つ。全式を乗算すると、

2^S \prod_{i = 1}^{L} V_i = \prod_{i = 1}^{L} (3V_{i - 1} + 1).

周期性 $V_L = V_0$ より、

\prod_{i = 1}^{L} V_i = \prod_{i = 1}^{L} V_{i - 1}.

したがって、

2^S = \prod_{i = 1}^{L} \left( 3 + \frac{1}{V_{i - 1}} \right).

を得る。

 各 $V_{i - 1}$ は正整数なので、

3 \lt 3 + \frac{1}{V_{i - 1}} \le 4.

よって、

3^L \lt 2^S \le 4^L.

が成り立つ。底 $2$ の対数を取り、$L$ で割ると、

\log_2 3 \lt \frac{S}{L} \le 2.

である。

$\lambda_x = S / L - 1$ より、

\log_2 \frac{3}{2} \lt \lambda_x \le 1.

を得る。一方、

\log_2 \frac{3}{2} = \log_{2}3 - 1 = \alphastar.

なので、これを代入すると、

\alphastar \lt \lambda_x \le 1.

である。

 また、上式で等号が成り立つ $\lambda_x = 1$ の場合、$2^S = 4^L$ である。
各因子は $4$ 以下であるため、積が $4^L$ に等しくなるには、すべての $i$ について、

3 + \frac{1}{V_{i - 1}} = 4.

でなければならない。したがって、すべての $i$ について $V_{i - 1} = 1$ である。
このとき $T_i = 2$ であり、循環経路は自明なループ $1 \mapsto 1$ である。

 したがって、命題は成り立つ。
$\square$

系3.3.2 (非自明循環経路の必要範囲). ◎💥
 非自明な正整数循環経路が存在するならば、

\alphastar \lt \lambda_x \lt 1.

が必要である。

証明.
 定理3.3.1 より、正整数循環経路では、$\alphastar \lt \lambda_x \le 1$ が成り立つ。
同定理の等号条件より、$\lambda_x = 1$ は自明なループに限られる。
したがって、非自明な循環経路では上端等号は成立しない。

 したがって、命題は成り立つ。
$\square$

3.3.3 cycle 長毎の周期最小値上界

 正整数循環経路の最小奇数値を、

m := \min_{0 \le i \lt L} V_i.

とする。また、

s_{\min}(L) := \left \lfloor L \log_{2} 3 \right \rfloor + 1.

と定める。

定理3.3.3 (cycle 長ごとの周期最小値上界). ◎💥
 正整数循環経路の長さを $L$ とし、

B_L :=
\max
\left\{
m \in \mathbb{N}
\ \middle |\
2^{s_{\min}(L)} m^L
\le
(3m + 1)^L
\right\}.

とする。このとき、当該循環経路の最小値 $m$ は、

m \le B_L.

を満たす。

証明.
 定理3.3.1 の証明で得た周期積恒等式より、

2^S = \prod_{i = 0}^{L - 1} \left( 3 + \frac{1}{V_i} \right).

$V_i \ge m$ であるから、

2^S \le \left( 3 + \frac{1}{m} \right)^L.

一方、$3^L \lt 2^S$ かつ $S \in \mathbb{Z}$ より、

S \ge s_{\min}(L).

したがって、

2^{s_{\min}(L)} \le \left( 3 + \frac{1}{m} \right)^L.

両辺に $m^L$ を乗じると、

2^{s_{\min}(L)} m^L \le (3m + 1)^L.

を得る。

 $L \ge 1$ では $s_{\min}(L) \le 2L$ であるため、$m = 1$ は、

2^{s_{\min}(L)} \le 4^L = (3 \cdot 1 + 1)^L.

を満たす。したがって、上式を満たす正整数集合は非空である。

 また、正整数 $m$ に対して $3 + 1/m$ は狭義単調減少であり、
$m \to \infty$ で $3$ に収束する。
 一方、$2^{s_{\min}(L)} \gt 3^L$ であるから、
上式を満たす正整数 $m$ は有限個である。
 よって、その最大値 $B_L$ は存在する。

 したがって、命題は成り立つ。
$\square$

3.3.4 finite circulation simple extreme-cycle 全長の有限還元

 法 $M = 2^b$ の derived logical $R$-graph に含まれる奇数状態数を、

N_M := \frac{M}{2}.

とする。

 ここでいう finite circulation は、§3.2.2で定義した
$E_M^{\mathrm{raw}}$ 上の非負正規化 circulation である。
$E_M^{\mathrm{raw}}$ は、exact $R$-micrograph の simple ODD-to-ODD path を
集約した有限集合であり、一般の全実 $R()$ 遷移を一辺ずつ収容することを
仮定しない。

補題3.3.4 (finite circulation extreme-cycle 長上界). ◎💥
 derived logical $R$-graph 上の非負正規化 circulation の extreme point は、
simple directed cycle の正規化 circulation に対応する。
したがって、その奇数遷移長 $L$ は、

1 \le L \le N_M.

を満たす。

証明.
 derived logical $R$-graph 上の任意の非零 circulation は、
補題3.2.1 により、simple directed-cycle circulation の
非負凸結合へ分解できる。
 二つ以上の互いに異なる正規化 cycle flow の非自明凸結合として
表される可行点は extreme point ではない。
 したがって、extreme point は一つの simple directed cycle の
正規化フローに対応する。

 simple directed cycle は同一奇数状態を重複して通過しない。
finite logical graph の奇数状態数は $N_M$ であるから、その長さは
$N_M$ 以下である。

 したがって、命題は成り立つ。
$\square$

 全長共通の周期最小値上界を、

B_M^{\mathrm{global}} := \max_{1 \le L \le N_M}B_L.

と定める。定理3.3.3 および 補題3.3.4 より、
derived logical $R$-graph の simple extreme-cycle 候補が
正整数周期軌道へ lift 可能ならば、その周期最小値は、

m \le B_M^{\mathrm{global}}.

を満たす。

3.4 周期最小値候補の完全有限監査

3.4.1 exact R-micrograph、derived logical R-graph と検査単位

 付録I の検証プログラムは、法 $M$ ごとに、任意の実 $R()$ 遷移を
有限辺列として追跡する exact $R$-micrograph を構成する。
 さらに、その micrograph から、内部 microstate を重複しない
一回の完全な ODD-to-ODD pathを全て列挙し、derived logical $R$-graphを
構成する。

 各logical edgeは、始点奇数状態、終点奇数状態、厳密な除算回数
$t_E(e)$、追加除算寄与 $a_E(e)$ および元の microedge 列を保持する。
したがって、logical edge は一回の完全な $R$-block candidate を表す。

 ただし、一般の実 $R()$ 遷移が常に一つの logical edge に
なるとは限らない。内部 microstate を重複する実遷移は、
exact $R$-micrograph 上の有限辺列として追跡されるが、
derived logical $R$-graph の一辺には集約されない。
 これは、derived logical $R$-graph の対象が、有限状態 LP の
simple extreme-cycle 候補だからである。

 正整数周期 lift を持つ simple logical cycle $C$ が存在する場合、
その定義より、$C$ の各 logical edge は同一の正整数周期軌道の連続する
一回の $R()$ 遷移として同時に実現される。
したがって、その実軌道の奇数遷移長は $C$ のlogical edge 数 $L$ に一致し、
周期最小値 $m$ が存在する。

 一方、周期最小値候補の最終監査では、有限状態 edge 列を
再生するのではなく、各正整数候補 $m$ に対して
exact integer arithmetic により $R()$ を直接適用する。
 したがって、この整数監査は、一般の実 $R()$ 遷移が logical edge として
一辺化されるか否かに依存しない。

3.4.2 全奇数最小値候補監査

 各奇数

1 \le m \le B_M^{\mathrm{global}}.

について、$m$ を周期最小値候補として、厳密整数演算により
$R()$ を最大 $N_M$ 回適用する。

 各候補を、次のいずれかへ分類する。

RETURNED_TO_START
    R^k(m) = m for some 1 \le k \le N_M.

DESCENDED_BELOW_START
    R^k(m) < m before returning to m

NO_RETURN_WITHIN_MAX_LENGTH
    no return to m during the first N_M odd transitions

 正整数周期軌道の最小値が $m$ で、その長さが $L \le N_M$ ならば、

R^L(m) = m

でなければならない。
したがって、DESCENDED_BELOW_START となった候補は
周期最小値になり得ず、NO_RETURN_WITHIN_MAX_LENGTH となった候補は
対象長以下で出発値へ戻らない。

 候補監査は、上界以下の全奇数を漏れなく処理する。
独立検証器は、全 $B_L$ と全奇数候補の $R()$ 遷移を再計算し、
監査結果を確認する。

3.4.3 完全有限監査による周期 lift 分類

 ここで、「完全有限監査」として標題に掲げた”完全”とは、
固定された有限状態グラフが、全てのコラッツ遷移を
個別の辺または辺列として無条件に一対一収容することを意味しない。
 本節までの一般定理より、finite circulation の simple extreme-cycle 候補の
正整数周期 lift が存在する場合、その周期長は $1 \le L \le N_M$ に、
その周期最小値は $m \le B_M^{\mathrm{global}}$ に限定される。
 したがって、「完全有限監査」とは、この論理的還元後に残る
全ての正整数周期 lift 候補が、上界以下の全奇数最小値候補の
監査によって漏れなく被覆されることを意味する。

定理3.4.1 (正整数周期 lift 完全分類定理). ◎💥
 法 $M$ について、次の全条件が独立検証付きで成立したとする。

  (1) exact $R$-micrograph の状態集合、microedge 集合および遷移構造が
    独立に確認される。

  (2) derived logical $R$-graph の logical edge 集合、
    各 edge の microedge 列、除算回数ラベルおよび graph hash が
    独立に確認される。

  (3) 補題3.2.1 および 補題3.3.4 に対応する
    finite circulation extreme-cycle bridge と、最大長 $N_M$ が
    確認される。

  (4) 全 $1 \le L\le N_M$ に対する $B_L$ と、その最大性が確認される。

  (5) 全奇数 $m \le B_M^{\mathrm{global}}$ が漏れなく監査される。

  (6) RETURNED_TO_START となる候補が $m = 1$ のみであり、
    その遷移が $1 \mapsto 1$, $T = (2)$ である。

 このとき、derived logical $R$-graph の simple extreme-cycle 候補の内、
正整数周期軌道へ lift 可能なものは、自明なループだけである。

証明.
 非自明な正整数周期liftを持つsimple extreme-cycle候補 $C$ が
存在すると仮定する。その長さを $L$、実周期軌道の最小値を $m$ とする。
補題3.3.4 より、$1 \le L \le N_M$ である。

 定理3.3.3 より、

m \le B_L \le B_M^{\mathrm{global}}.

したがって、$m$ は条件 (5) の監査対象に含まれる。

 $m$ は周期最小値であり、周期長 $L \le N_M$ で出発値へ戻るため
($R^L(m)=m$)、当該監査は RETURNED_TO_START と判定しなければ
ならない。条件 (6) より、RETURNED_TO_START となる候補は $m = 1$
のみであり、その復帰遷移は $1 \mapsto 1$, $T = (2)$ である。
よって $m=1$ である。

 実周期軌道上で最小値 $1$ をとる位置を $V_j = 1$ とすると、
$R(1) = 1$ より、

V_{j+1} = R(V_j) = R(1) = 1 = V_j.

 したがって、$C$ は奇数状態 $1$ の自己ループを含む。
simple cycle の定義より、自己ループを含む simple cycle の長さは
$L = 1$ に限られる。

 よって、$C$ は $1 \mapsto 1$, $T = (2)$ の自明なループそのもの
であり、非自明な周期 lift の存在仮定に反する。
 したがって、命題は成り立つ。
$\square$

3.5 2層 core certificate

 本章で扱う有限検査証明書を「周期 lift 構造有限検査証明書」と呼ぶ。

 周期 lift 構造有限検査証明書は、前節までに示した数学的な有限還元と、
その有限還元によって有限個に限定された全候補に対する完全監査および
独立検証を組み合わせて成立する。

 本節でいう2層 core certificateとは、周期 lift 構造有限検査証明書の
中核を構成し、有限検査の結果を役割の異なる2つの証拠層に分けて
束縛した証明書本体である。
 Layer 1 は正整数周期 lift 候補の完全分類とその独立検証結果を記録する。
Layer 2 は Layer 1 の分類結果から、構造値 $\lambda_x^{\mathrm{str}} = 1$ を
別の証拠生成処理および独立検証器によって再構成する。

 したがって、2層 core certificateは、前節までの数学的な有限還元を
代替するものではない。
 数学的な有限還元によって限定された全対象が漏れなく監査され、
その分類結果および構造値が独立検証によって確認されたことを示す、
有限検査証明の有限検査部分に対応する証拠本体である。

 以下では、2層 core certificate の論理構成、正式採用法における
確認結果および適用範囲を示す。

3.5.1 証明書の論理構成

 本章で採用する正式な core certificate は、次の2層から構成する。

Layer 1 : 正整数周期 lift の完全分類
Layer 2 : Layer 1 の分類結果から構造値 lambda_x^{str} = 1 を独立再構成

 Layer 1 は、定理3.4.1 の全条件と独立検証結果を束縛し、
次の正常状態を記録する。

PASS

 Layer 2 は、Layer 1 で残る唯一の有効 extreme structure が
$1\mapsto1$, $T = (2)$ であることを入力として、その構造値を厳密に
再構成し、次の正常状態を記録する。

PASS

 Layer 2 は、定理3.6.1 の結論を先に仮定する証明層ではない。
Layer 1 および§3.2.4 の定義から数学的に導かれる
$\Lambda_x(q) = 1$ および $\lambda_x^{\mathrm{str}} = 1$ を、別の証拠生成処理と
独立検証器により再構成する確認層である。したがって、
定理3.6.1 の数学的前提は Layer 1 の完全分類であり、
Layer 2 はその結論に対する独立な再計算証拠として位置付ける。

3.5.2 正式採用法における確認結果

 周期 lift 構造有限検査証明書として、正式に採用する法を、

b = 12, \qquad M = 2^{12} = 4096, \qquad N_M = 2048.

とする。通常のモード表現では、$M = 4096$ である。

 付録I に収録された検証プログラムの完全検証により、下表に示す
周期 lift 構造有限検査証明書が生成された。
これが正式採用法における実際の確認結果である。
 見るべき要点は、以下である。

structural value lambda_x^str fixed judgment       : Fixed

 これは、コラッツ遷移に対して期待される構造値($\lambda_{x,\mathrm{expected}}^{\mathrm{str}} = 1$)が
確定していることを示す。このことにより、後述の
「有効 LP 可行解構造定理」が成り立つことが保証される。

 なお、周期 lift 構造有限検査証明書の
詳細(各項目と説明、値の意味等)については、付録I を参照されたい。

  [表3.5.1]周期 lift 構造有限検査証明書

finite-check certificate id                        : LIC-APPENDIX-I-CORE-CERTIFICATE-v7
package label                                      : X04a-D01
b                                                  : 12
M                                                  : 4096
N_M                                                : 2048
certificate author id                              : cc28ae4b-b063-45af-ac0d-0ef67e0325e6
certificate generation operator id                 : cc28ae4b-b063-45af-ac0d-0ef67e0325e6
certificate verification operator id               : cc28ae4b-b063-45af-ac0d-0ef67e0325e6
certificate generator program id                   : LIC_appendix_i_core_certificate
certificate verifier program id                    : LIC_appendix_i_core_certificate_verifier
finite-check certificate created at                : 2026-08-02 18:01:15 JST
finite-check certificate verified at               : 2026-08-02 18:01:19 JST
finite-check certificate verification status       : PASS
exact R-micrograph state count                     : 6144
exact R-micrograph microedge count                 : 10240
exact R-micrograph hash payload fields             : M, states, edges
exact R-micrograph SHA-256                         : 51383ba07bc502baafdc12f659bc6cb6a8e8c10e0d612501d43494c598150cbb
exact R-micrograph state-set verify                : PASS
exact R-micrograph microedge-set verify            : PASS
exact R-micrograph transition verify               : PASS
exact R-micrograph independent verify              : PASS
derived logical R-graph odd state count            : 2048
derived logical R-graph logical edge count         : 26624
derived logical R-graph hash payload fields        : edge_id, src, dst, t, additional_division_cost, transformed_weight, micro_edge_ids
derived logical R-graph SHA-256                    : 2e31bc56f384b844439158e1bf70c543d980bce48065fb5029e58ccc46d0f690
derived logical R-graph odd-state-set verify       : PASS
derived logical R-graph edge-set verify            : PASS
logical-edge microedge-sequence verify             : PASS
logical-edge division-label verify                 : PASS
derived logical R-graph hash-binding verify        : PASS
derived logical R-graph independent verify         : PASS
finite circulation bridge graph binding verify     : PASS
finite circulation bridge length verify            : PASS
finite circulation bridge independent verify       : PASS
minimum-bound length rows                          : 2048
global minimum-value bound B_M^global              : 583287
global bound attained at L                         : 1636
minimum-bound lengths SHA-256                      : dc42e09ef7af729a143ba5ba537e7b7e7b686501e242d8278b2bec24f645bb9f
all-length bounds exact/maximal verify             : PASS
global minimum-value bound verify                  : PASS
global-bound argmax verify                         : PASS
minimum-bound independent verify                   : PASS
odd minimum candidates expected                    : 291644
odd minimum candidates audited                     : 291644
odd minimum candidate coverage complete            : PASS
candidate-count independent verify                 : PASS
candidate-blocks independent verify                : PASS
minimum-candidate audit independent verify         : PASS
RETURNED_TO_START                                  : 1
nontrivial returned candidates                     : 0
DESCENDED_BELOW_START                              : 291643
NO_RETURN_WITHIN_MAX_LENGTH                        : 0
trivial loop                                       : 1 -> 1, T = (2)
terminal-counts independent verify                 : PASS
returned-cycle details independent verify          : PASS
nontrivial-return-zero independent verify          : PASS
trivial-loop-only independent verify               : PASS
Layer 1 independent verify                         : PASS
Layer 2 independent verify                         : PASS
structural value lambda_x^str                      : 1
expected structural value lambda_x^str             : 1
structural value lambda_x^str set                  : {1}
structural value lambda_x^str fixed judgment       : Fixed
structural value fixed judgment independent verify : PASS
core certificate independent verify                : PASS
core certificate verified at                       : 2026-08-02 18:01:19 JST

■構造値の確定判定
 周期 lift 構造有限検査証明書における構造値の確定判定の仕様を
以下に示す。
 なお、構造値の確定判定は、周期 lift 構造有限検査証明書の結果を
縛る性格のものではなく、後続で示す「有効 LP 可行解構造定理」の
期待値としての位置付けである。

 本節では、第 3 章の論理から期待される構造値を、

\lambda_{x,\mathrm{expected}}^{\mathrm{str}} = 1

とする。
 ただし、この期待値は、有限検査における探索条件、候補除外条件
または構造値の計算条件には用いない。
 検証プログラムは、期待値とは独立に、正整数周期 lift 候補の完全分類を
実行し、その分類結果から有効な正整数周期 lift extreme structure の
構造値を再構成する。

 Layer 1 により正整数周期 lift 候補の完全分類が成立し、全候補の監査が
完了して未判定候補が存在せず、さらに Layer 2 により有効な
全 extreme structure から得られる構造値の集合が、独立に、

\left\{\lambda_x^{\mathrm{str}}\right\}=\left\{1\right\}

と再構成された場合、構造値は、

\lambda_x^{\mathrm{str}}=1

に確定したものとする。この総合判定を Fixed と呼ぶ。

 したがって、Fixed の判定条件は、次のすべてが成立することである。

  • 正整数周期 lift 候補の監査範囲が完全である。
  • 監査対象の全候補が判定済みである。
  • Layer 1 の完全分類が独立検証に合格している。
  • 有効な正整数周期 lift extreme structure が漏れなく確定している。
  • Layer 2 が、それらすべての構造値を独立に再構成している。
  • 再構成された構造値の集合が厳密に単集合 ({1}) である。
  • 再構成結果が期待値 $\lambda_{x,\mathrm{expected}}^{\mathrm{str}}=1$ と一致している。

 前提となる証拠または独立検証が成立していない場合は、
構造値が1でないと判定するのではなく、Fixed 判定そのものが
未成立であるとする。


 周期 lift 構造有限検査証明書と 定理3.4.1 の条件との対応は、
次の通りである。以下の対応表における判定状態を次のように定める。

  • PASS:条件が要求する全証拠項目が存在し、期待値との整合および
    独立検証がすべて正常に成立している。
  • FAIL:条件が要求する証拠項目の少なくとも一つについて、
    不一致または検証失敗が確認されている。
  • UNVERIFIED:証拠項目の欠落、未実行、処理中断または
    異常終了等により、条件の成立を確定できない。

 以下に示す条件 (1) ~ (6) がすべて PASS である場合に限り、
定理3.4.1 の適用条件は満たされる。
 少なくとも一つが FAIL または UNVERIFIED である場合、
定理3.4.1 を適用しない。
 ただし、UNVERIFIED は当該条件の否定を意味しない。

  [表3.5.2]周期 lift 構造有限検査証明書と定理3.4.1 の対応関係

条件 定理3.4.1 の要求事項 対応する証明書項目 判定
(1) exact $R$-micrograph の状態集合、microedge 集合および遷移構造が独立に確認される。 exact R-micrograph state count = 6144
exact R-micrograph microedge count = 10240
exact R-micrograph state-set verify = PASS
exact R-micrograph microedge-set verify = PASS
exact R-micrograph transition verify = PASS
exact R-micrograph independent verify = PASS
〇
(2) derived logical $R$-graph の logical edge 集合、各 edge の microedge 列、除算回数ラベルおよび graph hash が独立に確認される。 derived logical R-graph odd state count = 2048
derived logical R-graph logical edge count = 26624
derived logical R-graph odd-state-set verify = PASS
derived logical R-graph edge-set verify = PASS
logical-edge microedge-sequence verify = PASS
logical-edge division-label verify = PASS
derived logical R-graph hash-binding verify = PASS
derived logical R-graph independent verify = PASS
〇
(3) 補題3.2.1 および 補題3.3.4 に対応する finite circulation extreme-cycle bridge と、最大長 $N_M$ が確認される。 N_M = 2048
finite circulation bridge graph binding verify = PASS
finite circulation bridge length verify = PASS
finite circulation bridge independent verify = PASS
〇
(4) 全 $1 \le L \le N_M$ に対する $B_L$ と、その最大性が確認される。 minimum-bound length rows = 2048
global minimum-value bound B_M^global = 583287
global bound attained at L = 1636
all-length bounds exact/maximal verify = PASS
global minimum-value bound verify = PASS
global-bound argmax verify = PASS
minimum-bound independent verify = PASS
〇
(5) 全奇数 $m \le B_M^{\mathrm{global}}$ が漏れなく監査される。 odd minimum candidates expected = 291644
odd minimum candidates audited = 291644
odd minimum candidate coverage complete = PASS
candidate-count independent verify = PASS
candidate-blocks independent verify = PASS
minimum-candidate audit independent verify = PASS
〇
(6) RETURNED_TO_START となる候補が $m = 1$ のみであり、その遷移が $1 \mapsto 1,\ T = (2)$ である。 RETURNED_TO_START = 1
nontrivial returned candidates = 0
DESCENDED_BELOW_START = 291643
NO_RETURN_WITHIN_MAX_LENGTH = 0
trivial loop = 1 -> 1, T = (2)
terminal-counts independent verify = PASS
returned-cycle details independent verify = PASS
nontrivial-return-zero independent verify = PASS
trivial-loop-only independent verify = PASS
〇

(凡例)
  〇:PASS
  ×:FAIL
  ー:UNVERIFIED

 以上より、定理3.4.1 の条件(1)~(6)は独立検証を含めて満たされる。
したがって、定理3.4.1 は成り立つ。
 すなわち、derived logical $R$-graph の simple extreme-cycle 候補の内、
正整数周期軌道へ lift 可能なものは、自明なループに限られる。

3.5.3 本証明書の適用範囲

 core certificate が直接確立する対象は、

M = 4096 derived logical R-graph simple extreme-cycle
positive-integer periodic-lift complete classification
and the resulting structural value lambda_x^str = 1

である。

 また、本証明書単独では、無制限の非周期無限経験フローについて、
平均追加除算回数の下界を直接主張しない。そのような適用には、
対象フローが本章の $\mathcal{Q}_M^{\mathrm{eff}}$ へ属することを別途示す必要がある。

3.6 有効 LP 可行解構造定理

 本節では、正式採用法 $M=4096$ に対して成立した付録Iの
core certificate Layer 1 による正整数周期 lift 候補の完全分類を
基礎として、有効 LP 可行解の構造を確定する。

 Layer 1 の完全分類結果によれば、derived logical $R$-graph の
simple extreme-cycle 候補のうち、正整数周期軌道へ lift 可能なものは、
奇数状態 $1$ の自明なループだけである。
 したがって、正整数周期 lift を持つ simple directed cycle 全体 $\mathcal{C}_M^{\mathrm{lift}}$ は
当該 cycle のみからなり、その正規化 cycle flow の凸包として定義された
有効 LP 可行領域 $\mathcal{Q}_M^{\mathrm{eff}}$ も一つの正規化 flow だけからなる。

 以下では、この分類結果から、任意の $q\in\mathcal{Q}_M^{\mathrm{eff}}$ について
$\Lambda_x(q)=1$ が成立し、構造下界値が $\lambda_x^{\mathrm{str}}=1$ に確定することを示す。
なお、付録Iの Layer 2 は、この数学的帰結を独立に再構成して確認する
証拠層であり、本節の構造定理における数学的前提には含めない。

 次節では、本節で得られる有限状態構造の完全分類結果を、
自然数上の任意の循環経路へ適用するため、自然数循環経路から
有限検査体系へ至る mapping と、正整数周期 lift の categorization を
区別し、その処理過程における循環経路存在保存性を示す。

定理3.6.1 (有効 LP 可行解構造定理). ◎
 正式採用法について、付録I の core certificate Layer 1 が
独立検証を含めて正常に成立するとき、次が成り立つ。

  (1) 正整数周期liftを持つderived logical $R$-graph の
    simple extreme-cycle 候補は、自明なループだけである。
  (2) $\mathcal{C}_M^{\mathrm{lift}}$ は、自明なループに対応する simple cycle だけからなる。
  (3) 任意の $q \in \mathcal{Q}_M^{\mathrm{eff}}$ は自明なループの正規化 cycle フローに一致する。
  (4) 任意の $q \in \mathcal{Q}_M^{\mathrm{eff}}$ について、$\Lambda_x(q) = 1$ が成り立つ。
  (5) 構造下界値は、$\lambda_x^{\mathrm{str}} = 1$ である。

 なお、付録I の Layer 2 は、(4) および (5) を独立に再構成して
確認する証拠層であり、本定理の数学的仮定には含めない。

証明.
 定理3.4.1 および 付録I の Layer 1 証明書より、正整数周期 lift を持つ
simple extreme-cycle 候補は自明なループのみである。
したがって、$\mathcal{C}_M^{\mathrm{lift}}$ は当該 cycle のみからなる。

 §3.2.4 の定義より、$\mathcal{Q}_M^{\mathrm{eff}}$ は$\mathcal{C}_M^{\mathrm{lift}}$ に属する正規化 cycle フローの
凸包である。
 一つの点の凸包はその点自身であるから、
任意の $q \in \mathcal{Q}_M^{\mathrm{eff}}$ は自明なループの正規化フローに一致する。

 自明なループでは、除算回数は $T = 2$ であり、
一段の追加除算寄与は $2 - 1 = 1$ である。したがって、

\Lambda_x(q) = 1.

よって、

\lambda_x^{\mathrm{str}} = \inf_{q \in \mathcal{Q}_M^{\mathrm{eff}}} \Lambda_x(q) = 1.

 付録I の Layer 2 証明書は、この導出結果を独立に再構成し、
Layer 1 からの数学的帰結と一致することを確認する。

 したがって、命題は成り立つ。
$\square$

系3.6.2 (自然数循環構造分類系). ◎💥
 自然数のみで構成される循環経路から誘導される有限状態構造が、
正式採用法の derived logical $R$-graph の simple extreme-cycle 候補へ
対応する場合、その構造は自明なループに由来するものに限られる。

証明.
 仮定された有限状態構造は、周期 lift を持つ
simple extreme-cycle 候補である。
 定理3.6.1 の (1) より、その候補は自明なループのみである。

 したがって、命題は成り立つ。
$\square$

系3.6.3 (有効 LP 構造値系). ◎💥
 任意の $q \in \mathcal{Q}_M^{\mathrm{eff}}$ について、

\Lambda_x(q) = 1, \qquad \lambda_x^{\mathrm{str}} = 1.

が成り立つ。特に、

\lambda_x^{\mathrm{str}} \ge 1.

である。

証明.
 定理3.6.1 の (4) および (5) より直ちに従う。

 したがって、命題は成り立つ。
$\square$

3.7 有限状態 mapping における軌道情報保存

 本節では、自然数上の奇数コラッツ遷移列を有限状態表現へ写す
mapping が、元の遷移列の有限接頭辞に付随する軌道情報を
保持することを示す。

 ここで扱う mapping は、実際の奇数コラッツ遷移を
exact $R$-micrograph 上の有限辺列へ射影する処理に限定する。
 正整数周期 lift の有無、有限範囲化後の候補分類、
Layer 1 の全候補監査等は、この mapping そのものではなく、
mapping 後の対象に対して行う categorization または有限検査処理である。

 したがって、本節では、循環性、非循環性、無限性、発散性または
極限値等を mapping によって直接保存される性質として、
一括して扱わない。
 本節が扱うのは、任意の有限接頭辞について直接確認できる
遷移順序、除算指数、有限状態 trace、始終状態および辺通過回数等の
軌道情報である。

定義3.7.1 (有限奇数コラッツ遷移列).
 任意の $N \in \mathbb{Z}_{ \ge 1 }$ に対し、正の奇数からなる有限列

\Gamma_N
=
\left(
V_0, V_1, \ldots, V_N
\right)

が、

V_{i + 1} = R(V_i)
\qquad
(i = 0, 1, \ldots, N - 1).

を満たすとき、$\Gamma_N$ を長さ $N$ の有限奇数コラッツ遷移列と呼ぶ。

 また、各実遷移 $V_i \mapsto V_{i + 1}$ に対応する除算指数を、

T_i
=
\operatorname{ord}_2
\left(
3V_i + 1
\right)
\qquad
(i = 0, 1, \ldots, N - 1).

とする。

定義3.7.2 (有限状態 trace mapping).
 正式採用法について、有限奇数コラッツ遷移列

\Gamma_N
=
\left(
V_0, V_1, \ldots, V_N
\right).

を考える。

 各実遷移

V_i \mapsto V_{i + 1}.

を exact $R$-micrograph 上で正確に追跡する有限辺列を

\pi_i^{(M)}.

とする。このとき、ordered concatenation

\Psi_M(\Gamma_N)
=
\pi_0^{(M)}
\pi_1^{(M)}
\cdots
\pi_{N - 1}^{(M)}.

を、$\Gamma_N$ の有限状態 trace mappingと呼ぶ。

 有限状態 trace mapping $\Psi_M$ は、各実 $R()$ 遷移を
一つの logical edge として表すことを要求しない。
 内部 microstate を重複する実遷移についても、exact $R$-micrograph 上の
有限辺列として追跡し、その有限辺列を実遷移の trace として用いる。

定義3.7.3 (有限接頭辞軌道情報保存性).
 有限状態 trace mapping $\Psi_M$ が有限接頭辞軌道情報保存的であるとは、
任意の有限奇数コラッツ遷移列

\Gamma_N
=
\left(
V_0, V_1, \ldots, V_N
\right).

について、次の情報が $\Psi_M(\Gamma_N)$ において消去または順序変更されない
ことをいう。

  1. 各実遷移 $V_i \mapsto V_{i + 1}$ の存在。
  2. 各実遷移の順序。
  3. 各実遷移に対応する除算指数 $T_i$。
  4. 各 trace の終状態と、その直後の trace の始状態との接続関係。
  5. 有限接頭辞の始状態および終状態。
  6. 各 microedge または有限状態 edge の通過回数。
  7. 除算指数その他の辺ラベルに関する有限加法和。

 この定義は、$\Psi_M(\Gamma_N)$ だけから元の自然数列を
一意に復元できることを要求しない。
 また、有限接頭辞を越える無限軌道の極限的性質が、
mapping だけによって確定することも要求しない。

補題3.7.4 (有限状態 mapping における有限接頭辞軌道情報保存性).
 正式採用法について、有限状態 trace mapping $\Psi_M$ は、
有限接頭辞軌道情報保存的である。

証明.
 任意の有限奇数コラッツ遷移列を、

\Gamma_N
=
\left(
V_0, V_1, \ldots, V_N
\right).

とする。

 exact $R$-micrograph は、任意の実 $R()$ 遷移を有限状態上の
有限辺列として正確に追跡する。
 したがって、各実遷移

V_i \mapsto V_{i + 1}.

には、その遷移を構成する microedge を遷移順に並べた
有限辺列 $\pi_i^{(M)}$ が対応する。

 有限状態 trace mapping $\Psi_M(\Gamma_N)$ は、これらの有限辺列を、
元の実遷移の順序に従って、

\pi_0^{(M)},
\pi_1^{(M)},
\ldots,
\pi_{N - 1}^{(M)}.

の順に連結したものである。
 したがって、各実遷移の存在および順序は、mapping の構成によって
保持される。

 また、各 $\pi_i^{(M)}$ は、対応する実遷移

V_i \mapsto V_{i + 1}.

の exact trace であるから、その除算指数 $T_i$ および各 microedge の
辺ラベルは、当該 trace に対応して保持される。
 よって、除算指数その他の辺ラベルに関する有限加法和も、
各 trace のラベルを遷移順に加算することにより保持される。

 さらに、$V_{i + 1}$ は第 $i$ 番目の実遷移の終点であると同時に、
第 $i + 1$ 番目の実遷移の始点である。
 したがって、隣接する trace の接続関係は、元の実遷移列の
接続関係に従って保持される。
 有限接頭辞の出発点は $V_0$ に対応し、到達点は $V_N$ に対応する。
したがって、有限接頭辞の両端点の対応関係も保持される。

 また、$\Psi_M(\Gamma_N)$ は全 trace の ordered concatenation であるから、
各 microedge または有限状態 edge の通過回数は、
この有限辺列中の出現回数として漏れなく数えられる。

 以上より、有限状態 trace mapping $\Psi_M$ は、定義3.7.3 に掲げた
有限接頭辞軌道情報を消去または順序変更しない。
 よって、$\Psi_M$ は有限接頭辞軌道情報保存的である。

 したがって、命題は成り立つ。
$\square$

 補題3.7.4 は、循環経路および無限経路のいずれについても、
その任意の有限接頭辞に適用できる。
 循環経路については、次節において周期復帰 witness の保存へ
専用化する。
 無限経路については、第 9 章において、有限接頭辞から構成される
遷移経験分布およびその部分列極限を有限状態 LP へ接続する際の
共通基盤として用いる。


3.8 有限状態構造分類の循環経路への適用

 本節では、補題3.7.4 により確立した有限接頭辞軌道情報保存性を、
自然数上の循環経路へ専用化する。
 さらに、循環経路から得られる閉じた流量を LP 可行構造として表し、
finite circulation extreme-cycle bridge、有限範囲化および Layer 1 の
全候補監査へ接続する。

 以下では、自然数上の循環経路から有限状態 LP 構造へ至る
mapping と、有限検査対象の正整数周期 lift の有無を判定する
categorization を区別する。

 mapping は、自然数上の循環経路を exact $R$-micrograph へ射影し、
対応する有限状態の閉じた流量を LP 可行構造として表し、
finite circulation extreme-cycle bridge により simple extreme structure の
有限な凸結合表示へ書き換えるまでの一連の対応をいう。

 一方、categorization は、数学的な有限還元後に得られる
全候補について、正整数周期 lift の有無を判定し、
その結果を分類する処理をいう。
 したがって、LP 実数緩和上にのみ存在し、正の奇数整数列へ
帰着しない構造は、自然数上の循環経路の存在保存を論じる際の
対象外である。

 本節では、自然数のみで構成される循環経路全体を、

\mathscr{C}^{\mathbb{N}}.

と書く。

定義3.8.1 (循環経路の有限検査対応).
 正式採用法について、自然数の循環経路

C
=
\left(
V_0, V_1, \ldots, V_{L - 1}, V_L = V_0
\right) \in \mathscr{C}^{\mathbb{N}}.

に対し、第 3 章および付録Iで構成された次の一連の対応を、

\Phi_M(C).

と書き、循環経路 $C$ の有限検査対応と呼ぶ。

  1. 定義3.7.2 の有限状態 trace mapping $\Psi_M$ により、各実 $R()$ 遷移を
    exact $R$-micrograph 上の有限辺列へ射影する。
  2. 循環経路から得られる有限状態の閉じた流量を、非負性、正規化および
    流量保存を満たす raw LP 可行構造として表す。
  3. その raw LP 可行構造を、finite circulation extreme-cycle bridge により、
    simple directed-cycle flow の有限な非負凸結合として再表示する。

 この定義における simple extreme structure への有限還元は、
同一の raw LP 可行構造を有限な凸結合として再表示するものである。
 したがって、この定義は、各 simple extreme structure が個別に
正整数周期 lift を持つことを要求しない。
 各構成部分の整数帰着性は、mapping 後の categorization によって
判定される。

定義3.8.2 (循環経路存在保存性).
 有限検査対応 $\Phi_M$ と、その後の有限範囲化および Layer 1 の
全候補監査からなる有限検査体系が循環経路存在保存的であるとは、任意の

C \in \mathscr{C}^{\mathbb{N}}.

について、$C$ の周期最小値を $m_C$ とし、$m_C$ から出発して
初めて $m_C$ へ復帰するまでの最小復帰周期を、

C_0
=
\left(
V_0 = m_C,
V_1,
\ldots,
V_{L_C - 1},
V_{L_C} = V_0
\right) \in \mathscr{C}^{\mathbb{N}}.

としたとき、$C_0$ を構成する正の奇数整数列が与える
周期復帰の witness が、有限検査体系の各処理によって消去または
選択的に監査対象外化されず、Layer 1 の監査結果に正整数周期復帰として
反映されることをいう。
 ここで、$L_C$ は、

R^{L_C}(m_C) = m_C.

を満たす最小の正整数、すなわち原始周期長である。

 また、最小復帰周期 $C_0$ の各遷移に対応する ordered $T$-pattern を、

T(C_0)
=
\left(
T_1, T_2, \ldots, T_{L_C}
\right).

とする。このとき、$C_0$ を構成する正の奇数整数列は、

\begin{aligned}
&m_C \in \mathbb{N}_{\mathrm{odd}}, \\
&R^{L_C}(m_C) = m_C, \\
&\operatorname{ord}_2
\left(
3R^{i - 1}(m_C) + 1
\right)
=
T_i
\qquad
(i = 1, 2, \ldots, L_C).
\end{aligned}

を満たす。

 有限検査体系が循環経路存在保存的であるとは、
この正整数周期復帰の witness が、有限検査体系の各処理によって、
消去または選択的に監査対象外化されずに、Layer 1 の監査結果に
正整数周期復帰として反映されることをいう。

補題3.8.3 (有限検査体系における循環経路存在保存性).
 正式採用法について、付録I の core certificate Layer 1 が
独立検証を含めて正常に成立するとする。
 このとき、第 3 章で構成された有限検査対応 $\Phi_M$ と、
その後の有限範囲化および Layer 1 の全候補監査からなる
有限検査体系は、循環経路存在保存的である。

証明.
 自然数のみで構成される任意の循環経路を $C$ とし、
その周期最小値を $m_C$ とする。
 また、$m_C$ から出発して初めて $m_C$ へ復帰するまでの最小復帰周期を、

C_0
=
\left(
V_0 = m_C,
V_1,
\ldots,
V_{L_C - 1},
V_{L_C} = V_0
\right) \in \mathscr{C}^{\mathbb{N}}.

とする。ここで、

V_i = R(V_{i - 1})
\qquad
(i = 1, 2, \ldots, L_C).

である。

 補題3.7.4 より、有限状態 trace mapping $\Psi_M$ は、
最小復帰周期 $C_0$ の全実遷移、その遷移順序、各除算指数、
隣接 trace の接続関係および始終状態を保持する。特に、

V_{L_C} = V_0.

という始終状態の一致は、有限状態 trace 上の閉包として保持される。

 したがって、最小復帰周期 $C_0$ の有限状態表現は閉じた流量を与える。
 この流量を全通過量で正規化すると、各辺の重みは非負であり、
全辺重みの総和は $1$ となる。
 さらに、各有限状態における流入回数と流出回数は一致するため、
流量保存条件が成立する。
 よって、最小復帰周期 $C_0$ から誘導される流量は、
raw LP 可行条件を満たす。

 次に、補題3.2.1 および finite circulation extreme-cycle bridge により、
この raw LP 可行構造は、有限個の正規化 simple directed-cycle flow の
非負凸結合として表される。
 これは、元の raw LP 可行構造を別の構造へ置換する、または
破棄する処理ではなく、

q = \sum_{j = 1}^{r} \alpha_j q^{C_j},
\qquad \alpha_j \ge 0,
\qquad \sum_{j = 1}^{r} \alpha_j = 1.

という同一構造の有限な再表示である。
 したがって、この段階に、循環経路 $C_0$ の存在に由来する構造を
選択的に消去する操作は存在しない。

 ここで、各 simple extreme structure が個別に
自然数へ帰着するか否かは、mapping の問題ではなく、
後段の正整数周期 lift categorization の問題である。
 自然数へ帰着しない構成部分は、LP 実数緩和上にのみ存在する
構造であり、自然数上の循環経路の存在保存の対象ではない。

 一方、最小復帰周期 $C_0$ 自身については、

R^{L_C}(m_C) = m_C.

が成立する。
 また、各段階の除算指数は、最小復帰周期 $C_0$ の実遷移によって
exact に与えられる。
 したがって、$C_0$ を構成する正の奇数整数列自身が、
正整数周期復帰の witness である。

 周期長上界および周期最小値上界は、正式採用法に対する
有限検査証明の全対象範囲を有限に確定するものであり、
循環経路の存在という性質を変更する処理ではない。

 また、Layer 1 の最小値候補監査は、当該有限検査証明の
全対象範囲に属する全奇数候補へ、同一の厳密整数監査を適用する
all-targeting の処理である。
 したがって、この段階にも、特定の循環経路、または
その周期最小値を選択的に監査対象から除外する処理はない。

 実際、最終監査は有限状態 edge 列の形式的な再生ではなく、
各正整数最小値候補に対して $R()$ を exact integer arithmetic により
直接適用する。
 したがって、最小復帰周期 $C_0$ が存在する場合、その復帰事実

R^{L_C}(m_C) = m_C.

は、Layer 1 において RETURNED_TO_START として検出される。

 以上より、有限状態 trace mapping、raw LP 可行化、
simple extreme structure への同値な再表示、有限範囲化および
全候補監査のいずれにも、自然数循環経路の存在を消失させる処理はない。
 よって、第 3 章で構成された有限検査対応 $\Phi_M$ と、
その後の有限範囲化および Layer 1 の全候補監査からなる有限検査体系は、
循環経路存在保存的である。

 したがって、命題は成り立つ。
$\square$

補題3.8.4 (自然数循環経路への有限状態構造分類の適用).
 正式採用法について、付録I の core certificate Layer 1 が
独立検証を含めて正常に成立するとする。
 このとき、自然数のみで構成される任意の循環経路は、

1 \mapsto 1, \qquad T = (2).

である自明なループの正の反復で構成される。
 したがって、その循環経路から誘導される有限状態構造は、
自明なループに由来するものに限られる。

証明.
 自然数のみで構成される任意の循環経路を $C$ とする。

 $C$ の周期最小値を $m_C$ とし、$m_C$ から出発して初めて
$m_C$ へ復帰するまでの最小復帰周期を、

C_0
=
\left(
V_0 = m_C,
V_1,
\ldots,
V_{L_C - 1},
V_{L_C} = V_0
\right) \in \mathscr{C}^{\mathbb{N}}.

とする。ここで、$L_C$ は、

R^{L_C}(m_C) = m_C.

を満たす最小の正整数であり、

V_i = R(V_{i - 1}) \qquad (i = 1, 2, \ldots, L_C).

である。

 補題3.8.3 より、有限検査対応 $\Phi_M$ と、その後の有限範囲化および
Layer 1 の全候補監査からなる有限検査体系は循環経路存在保存的である。
 したがって、最小復帰周期 $C_0$ を構成する正の奇数整数列が与える

R^{L_C}(m_C) = m_C

という周期復帰の witness は、Layer 1 の監査結果に
正整数周期復帰として反映される。

 ここで、付録I の core certificate Layer 1 による
完全監査および独立検証では、

RETURNED_TO_START              : 1
nontrivial returned candidates : 0
NO_RETURN_WITHIN_MAX_LENGTH    : 0
trivial loop                   : 1 -> 1, T = (2)
Layer 1 independent verify     : PASS

が確認されている。

 したがって、正整数周期復帰を持つ最小復帰周期は、

m_C = 1, \qquad L_C = 1, \qquad T(C_0) = (2).

の場合だけである。よって、最小復帰周期 $C_0$ は、

1 \mapsto 1

である自明なループそのものである。

 任意の循環経路 $C$ は、その最小復帰周期 $C_0$ の正の反復である。
したがって、自然数のみで構成される任意の循環経路は
自明なループの正の反復で構成される。
 よって、その循環経路から誘導される有限状態構造も
自明なループに由来するものに限られる。

 したがって、命題は成り立つ。
$\square$

////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?