docs(runtime): Phase 99 ログ/出力ポリシー確定 - 3層設計の文書化完成

## Phase 99 完了項目(ドキュメント設計フェーズ)
-  logging_policy.md 新規作成(312行)
-  ring0-inventory.md 更新(455行)
-  core_boxes_design.md Section 15.6-A 追記(+58行)
-  CURRENT_TASK.md Phase 85 セクション更新

## 確定した3層ログ/出力設計

【Ring0.log】(OS API層)
- 用途: ランタイム/OS内部ログ
- 対象: 開発者向けデバッグ・計測・内部状態
- API: ring0.log.debug/info/warn/error(...)

【ConsoleService】(Box層・ユーザー向け)
- 用途: CLIの直接的な出力(ユーザー向けメッセージ)
- 対象: エンドユーザー
- アクセス: console_println! マクロ

【素のprintln!/eprintln!】(制限用途)
- 用途: テスト・一時デバッグのみ限定
- テスト内: 約299箇所そのまま許可
- 本番経路: 撤退すべき

## println!/eprintln! 残件分類(1477箇所)
- user-facing: ~366箇所(HIGH)→ console_println!
- dev-debug: TBD(MEDIUM)→ Ring0.log or dev_* macros
- test: ~299箇所(LOW)→ そのまま許可
- internal: ~812箇所(TBD)

## 設計の価値
- **コード変更なし**: リスク最小(ドキュメントのみ)
- **後工程の基盤**: Phase 100-101で残り~366箇所を片付け可能
- **Fail-Fast原則**: マクロ方針でエラーメッセージは確実に出力
- **段階的移行**: Graceful Degradation パターンで初期化前後を対応

## 新規ドキュメント構成
logging_policy.md:
  - Section 1: 3層の役割分担
  - Section 2: Macroポリシー
  - Section 3: テスト内println!の扱い
  - Section 4: 完全統合の完了条件
  - Section 5: 設計原則
  - Section 6: 関連ドキュメント

ring0-inventory.md:
  - Section 1: Ring0.log利用状況
  - Section 2: println! 残件分類(4カテゴリ)
  - Section 3: Ring0.log活用計画
  - Section 4-8: 配布状況・ロードマップ・コマンド・履歴・成功基準

## AI協働開発の成功例
- 設計と実装の分離(Phase 99=設計、Phase 100+=実装)
- 段階的アプローチ(80/20ルール:完璧より進捗)
- ドキュメント優先(コードより先に設計を固める)

## Phase 85-99 総括
- Phase 95.5: StringService/ConsoleService実装
- Phase 96-96.5: ArrayService/MapService & コード整理
- Phase 97: IntegerService/BoolService(#[allow(dead_code)] 根絶)
- Phase 98-98.5: ConsoleService代表パス拡張(7箇所)
- Phase 99: ログ/出力ポリシー確定(設計フェーズ) 

次: Phase 100-101(user-facing移行、~366箇所段階的実装)

🎊 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
nyash-codex
2025-12-03 11:31:35 +09:00
parent 44c6ca9585
commit c181aeac4d
4 changed files with 798 additions and 374 deletions

View File

@ -1,424 +1,455 @@
# Ring0 Inventory(初回棚卸しメモ)
# Ring0 Inventory & println! Categorization (Phase 99)
このドキュメントは、Phase 85-ring0-runtime のための「Ring0 候補呼び出し」の棚卸しメモだよ。
ここでは Task 調査で分かった概況だけをまとめておき、詳細な一覧化や移行は後続フェーズで扱う。
## Overview
This document provides an inventory of Ring0.log infrastructure and categorizes the remaining println!/eprintln! call sites across the codebase. This inventory serves as the foundation for future migration planning.
**Status**: Design phase (Phase 99) - assessment and planning only, no code changes.
---
## 1. println!/eprintln! 呼び出し
## Section 1: Ring0.log Utilization Status
- `println!` / `eprintln!` の合計呼び出し回数: **3,955 回**
- デバッグログ/一時ログ/ユーザ向けメッセージが混在している。
- Ring0 の `LogApi` / `Console` 相当として、最優先で整理したい対象。
- 方針メモ:
- 将来的には `Ring0Context.log` / `Ring0Context.io` 経由に寄せる。
- 代表パスselfhost/hack_check/VM/LLVM`println!/eprintln!` から段階的に移行する。
### Current Infrastructure (Phase 99 Start)
### Phase 88 移行状況2025-12-02
**Implemented**:
- `Ring0Context` contains `log: Arc<dyn LogApi>`
- `LogApi` trait with methods:
- `debug(message: &str)`
- `info(message: &str)`
- `warn(message: &str)`
- `error(message: &str)`
- `StdLog` implementation outputs to stdout/stderr
**移行済みパス2箇所**:
| ファイル | 行 | Before | After |
|---------|---|--------|-------|
| `src/runner/selfhost.rs` | 27 | `eprintln!("[selfhost][oob-strict] ...")` | `ring0.log.error("[selfhost][oob-strict] ...")` |
| `src/runner/selfhost.rs` | 177 | `eprintln!("❌ PyVM error ...")` | `ring0.log.error("❌ PyVM error ...")` |
**残存パス3,953箇所**:
| カテゴリ | 出現回数 | 移行予定 |
|---------|---------|---------|
| println! | 2,200 | Phase 89-A |
| eprintln! | 1,753 | Phase 89-B |
Phase 89 以降で段階的に移行予定。
### Phase 89-A 移行状況2025-12-02
**移行済み56箇所**:
- **src/runner/selfhost.rs**: 11箇所を ring0.log.* に移行
- **src/runner/modes/vm.rs**: 22箇所を ring0.log.* に移行
- **src/runner/modes/vm_fallback.rs**: 4箇所を ring0.log.* に移行
- **src/runner/modes/common_util/hack_check.rs**: 19箇所を ring0.log.* に移行
**残存2,093箇所、main codebase のみ)**:
- 総数: 2,149箇所全体
- main codebase (src/ + crates/nyash_kernel/): 1,948箇所
- plugins: 201箇所別途対応
**Location**: `crates/nyash_kernel/src/ring0/log.rs`
---
## 2. Box / プラグイン / カーネル実装の数
### Phase 95-98 Usage
- `src/boxes`: 34 Box
- `plugins/`: 22 プラグイン
- `crates/nyash_kernel`: 12 カーネル実装
**ConsoleService Implementation (Phase 95-98)**:
- PluginHost established with CoreServices
- ConsoleService provides user-facing output
- `console_println!` macro consolidates user messages
- Ring0.log remains underutilized (future expansion target)
ざっくり分類案Phase 85 時点の暫定):
- core_required:
- StringBox, IntegerBox, BoolBox, ArrayBox, MapBox, ConsoleBox など、言語の基本型+コンソール。
- core_optional:
- FileBox, PathBox, RegexBox, MathBox, TimeBox, JsonBox, TomlBox など、標準ユーティリティ系。
- selfhost_required:
- Stage1CliBox, AotCompilerBox, MirJsonBuilderBox など、selfhost/Stage1 ライン専用。
- user_plugin:
- P2P, HTTP, GUI, Python 連携 等の外部拡張。
※ 正確な一覧とファイルパスは、後続フェーズで Box 定義ファイルを機械的に列挙して作る。
**Current Ring0.log Usage**: Minimal
- Primary logging still uses raw println!/eprintln!
- Opportunity for consolidation exists
---
## 3. Factory Priority 問題Phase 15.5 の再確認)
## Section 2: println!/eprintln! Remaining Call Sites
- 現状の Factory Priority が `BuiltinFirst`(ビルトイン優先)となっている箇所があり、
- プラグインで上書きしたいケースでも、ビルトイン版が優先されてしまう。
- これは:
- 「core_required な Box」と「user_plugin を使って差し替えたい Box」の境界が曖昧なことの副作用でもある。
- 方針メモ:
- Ring1-core の整理と合わせて、Factory Priority を
- core_required は常にビルトイン
- core_optional / user_plugin は設定やプロファイルで切り替え可能
に整理していく。
### Overall Statistics
**Total**: 1776 locations (Phase 99 initial assessment)
- Test code: ~299 locations
- Production code: ~1477 locations
**Source**: Phase 99 initial assessment via `rg 'println!|eprintln!'`
**Historical Context (Phase 88-90)**:
- Phase 88-90 migrated 56 locations to ring0.log.*
- Phase 90 migrated 12 locations to ring0.fs/time/thread.*
- Previous total: 3,955 locations → Current: 1,776 locations
---
## 4. 今後の棚卸しタスクTODO メモ)
### Category Breakdown (Design Phase)
- `std::fs` / `File::open` / `std::io::stdin` などの呼び出し地点を一覧化。
- `SystemTime::now` / `Instant::now` / `thread::sleep` など時間・スレッド系 API の呼び出し地点を一覧化。
- hakmem / nyrt 経由の低レベル API 呼び出しalloc/free など)を一覧化。
- 代表パスselfhost/hack_check/VM/LLVMのみを対象にした「最小 Ring0 呼び出しセット」を定義する。
#### Category 1: user-facing (~366 locations, HIGH priority)
**Description**: CLI messages, errors, help text, and other user-visible output
**Target Migration**: `console_println!` macro
**Priority**: HIGH (directly visible to end users)
**Phase 98 Progress**: 7 locations completed (representative paths)
**Phase 100-101 Plan**: Gradual expansion
**Example Locations**:
- `src/runner/` - CLI entry points
- Error messages in main execution paths
- Help text and usage information
- Progress indicators
---
## 3. IO/time 系 Ring0 候補Phase 89-B 調査結果)
#### Category 2: dev-debug (TBD, MEDIUM priority)
### 3.1 std::fs 系呼び出し
**Description**: Temporary debug output for development purposes
**調査日**: 2025-12-02
**Target Migration**: Ring0.log or dev_* macros (to be decided later)
- **総出現回数**: **243 箇所**(全体)
- **main codebase (src/ + crates/nyash_kernel/)**: **171 箇所**
- **plugins**: 72 箇所
**Priority**: MEDIUM
### 代表的な呼び出し
**Phase 99 Scope**: Assessment only - determine if Ring0.log is appropriate
| 関数 | 用途 | 推定回数 |
|------|------|----------|
| `std::fs::read_to_string()` | ファイル読み込み | 80+ |
| `std::fs::write()` | ファイル書き込み | 40+ |
| `std::fs::File::open()` | ファイルオープン | 30+ |
| `std::fs::File::create()` | ファイル作成 | 20+ |
| `std::fs::canonicalize()` | パス正規化 | 15+ |
| `std::fs::create_dir_all()` | ディレクトリ作成 | 15+ |
| `std::fs::metadata()` | ファイル情報取得 | 10+ |
**Decision Deferred**: Phase 100+
### 主要ファイルTop 20
| ファイル | 出現回数 | 移行優先度 |
|---------|---------|-----------|
| `src/runner/modes/common_util/resolve/strip.rs` | 13 | 高 |
| `src/runner/modes/common_util/exec.rs` | 5 | 高 |
| `src/runner/mod.rs` | 5 | 高 |
| `src/runner/stage1_bridge/mod.rs` | 4 | 中 |
| `src/runner/selfhost.rs` | 4 | 高 |
| `src/runner/modes/llvm.rs` | 4 | 中 |
| `src/runner/dispatch.rs` | 4 | 中 |
| `src/runner/pipe_io.rs` | 3 | 中 |
| `src/runner/modes/vm.rs` | 3 | 高 |
| `src/runner/modes/common_util/resolve/using_resolution.rs` | 3 | 中 |
### 移行方針Phase 90-A 案)
**優先経路**:
1. **src/runner/selfhost.rs** (4箇所) - セルフホスト実行経路
2. **src/runner/modes/vm.rs** (3箇所) - VM実行経路
3. **src/runner/modes/common_util/resolve/strip.rs** (13箇所) - 名前解決経路
**実装方針**:
- `ring0.io.file_read(path) -> Result<String, IoError>`
- `ring0.io.file_write(path, content) -> Result<(), IoError>`
- `ring0.io.file_open(path, mode) -> Result<FileHandle, IoError>`
- `ring0.io.dir_create(path) -> Result<(), IoError>`
**推定工数**: 10-20箇所の移行Phase 90-A
### 3.2 std::io 系呼び出し
**調査日**: 2025-12-02
- **総出現回数**: **87 箇所**(全体)
- **main codebase (src/ + crates/nyash_kernel/)**: **74 箇所**
- **plugins**: 13 箇所
### 代表的な呼び出し
| 関数 | 用途 | 推定回数 |
|------|------|----------|
| `std::io::Write` | 書き込みトレイト | 30+ |
| `std::io::Read` | 読み込みトレイト | 20+ |
| `std::io::stdin()` | 標準入力 | 10+ |
| `std::io::stdout()` | 標準出力 | 8+ |
| `std::io::stderr()` | 標準エラー | 5+ |
| `BufReader` | バッファ付き読み込み | 5+ |
| `BufWriter` | バッファ付き書き込み | 3+ |
### 主要ファイルTop 10
| ファイル | 出現回数 | カテゴリ |
|---------|---------|---------|
| `crates/nyash_kernel/src/plugin/console.rs` | 10+ | Ring1 candidate |
| `src/runner/core_executor.rs` | 3 | selfhost |
| `src/runner/stage1_bridge/mod.rs` | 5 | Stage1 |
| `src/runner/pipe_io.rs` | 3 | pipe I/O |
| `src/runtime/ring0/std_impls.rs` | 6 | **Ring0 impl** |
### 移行方針Phase 90-B 案)
**優先経路**:
1. **src/runtime/ring0/std_impls.rs** (6箇所) - 既存Ring0実装の統合
2. **src/runner/pipe_io.rs** (3箇所) - パイプ入出力経路
3. **crates/nyash_kernel/src/plugin/console.rs** (10箇所) - Ring1候補として保持
**実装方針**:
- `ring0.io.stdin_read() -> Result<String, IoError>`
- `ring0.io.stdout_write(s: &str) -> Result<(), IoError>`
- `ring0.io.stderr_write(s: &str) -> Result<(), IoError>`
**推定工数**: 5-10箇所の移行Phase 90-B
### 3.3 std::time 系呼び出し
**調査日**: 2025-12-02
- **総出現回数**: **143 箇所**(全体)
- **main codebase (src/ + crates/nyash_kernel/)**: **110 箇所**
- **plugins**: 33 箇所
### 代表的な呼び出し
| 関数 | 用途 | 推定回数 |
|------|------|----------|
| `std::time::Instant::now()` | 高精度タイマー | 40+ |
| `std::time::Duration` | 時間間隔 | 30+ |
| `elapsed()` | 経過時間計測 | 25+ |
| `std::time::SystemTime::now()` | システム時刻 | 10+ |
### 主要ファイルTop 15
| ファイル | 出現回数 | カテゴリ |
|---------|---------|---------|
| `src/runner/modes/bench.rs` | 18 | ベンチマーク |
| `src/boxes/sound_box.rs` | 11 | Box実装 |
| `src/mir/join_ir/lowering/if_dry_runner.rs` | 8 | JoinIR |
| `src/boxes/time_box.rs` | 8 | Box実装 |
| `src/boxes/socket_box.rs` | 7 | Box実装 |
| `src/runtime/global_hooks.rs` | 6 | ランタイム |
| `src/macro/macro_box_ny.rs` | 5 | マクロ |
| `src/runner/modes/common_util/selfhost_exe.rs` | 4 | selfhost |
| `src/runner/modes/common_util/io.rs` | 4 | I/O |
| `src/backend/aot/compiler.rs` | 4 | AOT |
### 移行方針Phase 90-C 案)
**優先経路**:
1. **src/runner/modes/common_util/io.rs** (4箇所) - タイムアウト制御
2. **src/runner/modes/common_util/selfhost_exe.rs** (4箇所) - セルフホスト実行
3. **src/runtime/global_hooks.rs** (6箇所) - ランタイムフック
**実装方針**:
- `ring0.time.now() -> Result<SystemTime, TimeError>`
- `ring0.time.monotonic_now() -> Result<Instant, TimeError>`
- `ring0.time.elapsed(start: Instant) -> Duration`
- `ring0.time.sleep(ms: u64) -> Result<(), TimeError>`
**推定工数**: 10-15箇所の移行Phase 90-C
### 3.4 thread 系呼び出し
**調査日**: 2025-12-02
- **総出現回数**: **37 箇所**(全体)
- **main codebase (src/ + crates/nyash_kernel/)**: **26 箇所**
- **plugins**: 11 箇所
### 代表的な呼び出し
| 関数 | 用途 | 推定回数 |
|------|------|----------|
| `std::thread::sleep()` | スリープ | 20+ |
| `std::thread::spawn()` | スレッド生成 | 10+ |
| `JoinHandle` | スレッド待機 | 5+ |
### 主要ファイルTop 10
| ファイル | 出現回数 | カテゴリ |
|---------|---------|---------|
| `src/boxes/sound_box.rs` | 11 | Box実装 |
| `src/boxes/p2p_box.rs` | 4 | Box実装 |
| `src/boxes/socket_box.rs` | 1 | Box実装 |
| `src/runtime/global_hooks.rs` | 2 | ランタイム |
| `src/runtime/plugin_loader_unified.rs` | 2 | プラグイン |
| `src/macro/macro_box_ny.rs` | 1 | マクロ |
### 移行方針Phase 90-D 案)
**優先経路**:
1. **src/runtime/global_hooks.rs** (2箇所) - ランタイムフック
2. **src/boxes/sound_box.rs** (11箇所) - Ring1候補として保持
3. **src/boxes/p2p_box.rs** (4箇所) - Ring1候補として保持
**実装方針**:
- `ring0.thread.sleep(ms: u64) -> Result<(), ThreadError>`
- `ring0.thread.spawn<F>(f: F) -> Result<ThreadHandle, ThreadError>`
- `ring0.thread.join(handle: ThreadHandle) -> Result<(), ThreadError>`
**推定工数**: 3-5箇所の移行Phase 90-D
**Considerations**:
- Is this debug output needed in production?
- Should it use Ring0.log.debug()?
- Or should it be removed entirely?
- Or should it use a special dev_* macro?
---
## 4. Phase 90 実装計画案
#### Category 3: test (~299 locations, LOW priority)
### Phase 90-A: fs 系移行(推定 10-20箇所
**Description**: Test output and verification messages
**対象**:
- src/runner/selfhost.rs (4箇所)
- src/runner/modes/vm.rs (3箇所)
- src/runner/modes/common_util/resolve/strip.rs (13箇所)
**Target Migration**: **None - keep as-is**
**実装**:
- `ring0.io.file_open(path, mode)`
- `ring0.io.file_read(path)`
- `ring0.io.file_write(path, content)`
- `ring0.io.dir_create(path)`
**Priority**: LOW (safe in isolated environment)
**推定工数**: 2-3時間
**Phase 99-101 Plan**: No changes
### Phase 90-B: io 系移行(推定 5-10箇所
**Rationale**:
- Tests run in isolated environments
- println! is appropriate for test output
- No migration needed
**対象**:
- src/runtime/ring0/std_impls.rs (6箇所)
- src/runner/pipe_io.rs (3箇所)
**実装**:
- `ring0.io.stdin_read()`
- `ring0.io.stdout_write(s)`
- `ring0.io.stderr_write(s)`
**推定工数**: 1-2時間
### Phase 90-C: time 系移行(推定 10-15箇所
**対象**:
- src/runner/modes/common_util/io.rs (4箇所)
- src/runner/modes/common_util/selfhost_exe.rs (4箇所)
- src/runtime/global_hooks.rs (6箇所)
**実装**:
- `ring0.time.now()`
- `ring0.time.monotonic_now()`
- `ring0.time.elapsed(start)`
- `ring0.time.sleep(ms)`
**推定工数**: 2-3時間
### Phase 90-D: thread 系移行(推定 3-5箇所
**対象**:
- src/runtime/global_hooks.rs (2箇所)
- src/runtime/plugin_loader_unified.rs (2箇所)
**実装**:
- `ring0.thread.sleep(ms)`
- `ring0.thread.spawn(f)`
- `ring0.thread.join(handle)`
**推定工数**: 1-2時間
### Phase 90-E: 統合テスト
**対象**:
- selfhost 実行経路の完全動作確認
- VM/LLVM バックエンドの動作確認
- プラグインロードの動作確認
**推定工数**: 2-3時間
### Phase 90 総推定工数
**合計**: 8-13時間約1-2日
**完了条件**:
- ✅ 全 Ring0 候補の移行完了
- ✅ テスト全パス
- ✅ println!/eprintln! 残存 1,948箇所以下Phase 89-A から追加なし)
**Example Locations**:
- Test assertion messages
- Test progress indicators
- Debug output during test execution
---
## 5. Phase 90 移行実績2025-12-03
#### Category 4: internal (~812 locations, TBD)
### Phase 90-A: fs 系移行7箇所
**Description**: Internal processing println! remnants
**FsApi trait 追加**:
- `read_to_string()`, `read()`, `write_all()`, `exists()`, `metadata()`, `canonicalize()`
**Target Migration**: TBD
**移行済みパス**:
**Priority**: To be determined in Phase 99
| ファイル | 行 | 移行内容 |
|---------|---|---------|
| `src/runner/modes/common_util/resolve/strip.rs` | 550-555 | `std::fs::read_to_string``ring0.fs.read_to_string` |
| `src/runner/modes/common_util/resolve/strip.rs` | 650-655 | `std::fs::read_to_string``ring0.fs.read_to_string` |
| `src/runner/modes/common_util/resolve/strip.rs` | 901-906 | `std::fs::read_to_string``ring0.fs.read_to_string` |
| `src/runner/modes/common_util/resolve/strip.rs` | 941-946 | `std::fs::read_to_string``ring0.fs.read_to_string` |
| `src/runner/dispatch.rs` | 31-33 | `std::fs::read_to_string``ring0.fs.read_to_string` |
| `src/runner/mod.rs` | 122-124 | `std::fs::read_to_string``ring0.fs.read_to_string` |
| `src/runner/mod.rs` | 181-183 | `std::fs::read_to_string``ring0.fs.read_to_string` |
| `src/runner/mod.rs` | 288-290 | `std::fs::read_to_string``ring0.fs.read_to_string` |
**Phase 99 Scope**: Initial categorization
**移行進捗**: 7/243箇所 (2.9%)
### Phase 90-B: io 系移行
Phase 88 で既に IoApi 実装済みのため、スキップstdin/stdout は既存の ring0.io.* を使用)。
### Phase 90-C: time 系移行3箇所
**TimeApi に elapsed() 追加**:
- `fn elapsed(&self, start: Instant) -> Duration`
**移行済みパス**:
| ファイル | 行 | 移行内容 |
|---------|---|---------|
| `src/runner/modes/common_util/selfhost_exe.rs` | 60-68 | `Instant::now() + elapsed()``ring0.time.monotonic_now() + ring0.time.elapsed()` |
| `src/runner/modes/common_util/io.rs` | 22-37 | `Instant::now() + elapsed()``ring0.time.monotonic_now() + ring0.time.elapsed()` |
| `src/runtime/plugin_loader_unified.rs` | 330-344 | `Instant::now() + elapsed()``ring0.time.monotonic_now() + ring0.time.elapsed()` |
**移行進捗**: 3/143箇所 (2.1%)
### Phase 90-D: thread 系移行2箇所
**ThreadApi trait 追加**:
- `fn sleep(&self, duration: Duration)`
**移行済みパス**:
| ファイル | 行 | 移行内容 |
|---------|---|---------|
| `src/runtime/global_hooks.rs` | 246-253 | `std::thread::sleep``ring0.thread.sleep` |
| `src/runtime/plugin_loader_unified.rs` | 342 | `std::thread::sleep``ring0.thread.sleep` |
**移行進捗**: 2/37箇所 (5.4%)
**Subcategories** (to be refined):
- Internal errors (could use Ring0.log.error)
- State transitions (could use Ring0.log.debug)
- Legacy debug output (could be removed)
- Performance metrics (could use Ring0.log.info)
---
## 6. 今後の棚卸しタスクPhase 91 以降)
## Section 3: Ring0.log Expansion Plan (Sketch)
- hakmem / nyrt 経由の低レベル API 呼び出しalloc/free など)を一覧化。
- 代表パスselfhost/hack_check/VM/LLVMのみを対象にした「最小 Ring0 呼び出しセット」を定義する。
- Ring1-core の境界整理core_required / core_optional / user_plugin
### Future Directions (Not Implemented)
これらは Phase 8687 で Ring0Context に寄せていくための下準備だよ。
This section outlines **potential** future uses of Ring0.log. Implementation is deferred to Phase 100+.
---
#### Option 1: Error Log Consolidation
**Concept**: Unify error logging through Ring0.log
**Examples**:
```rust
// VM execution errors
ring0.log.error(&format!("VM execution failed: {}", err));
// Parser errors
ring0.log.error(&format!("Parse error at line {}: {}", line, msg));
// MIR lowering errors
ring0.log.error(&format!("Lowering failed for {}: {}", node, reason));
```
**Benefits**:
- Centralized error logging
- Consistent error format
- Easy to redirect to files or monitoring systems
**Phase 99 Decision**: Concept documented, implementation deferred
---
#### Option 2: Internal State Logging
**Concept**: Use Ring0.log for runtime state tracking
**Examples**:
```rust
// Memory usage
ring0.log.debug(&format!("Memory allocated: {} bytes", size));
// GC triggers
ring0.log.info("Garbage collection triggered");
// Cache events
ring0.log.debug(&format!("Cache hit rate: {}%", rate));
```
**Benefits**:
- Non-intrusive diagnostics
- Performance monitoring
- Debugging production issues
**Phase 99 Decision**: Concept documented, implementation deferred
---
#### Option 3: Execution Tracing
**Concept**: Trace program execution through Ring0.log
**Examples**:
```rust
// Function entry/exit
ring0.log.debug(&format!("Entering function: {}", name));
// State transitions
ring0.log.info(&format!("State changed: {} -> {}", old, new));
// Performance markers
ring0.log.debug(&format!("Operation completed in {}ms", duration));
```
**Benefits**:
- Detailed execution visibility
- Performance profiling
- Bug reproduction
**Phase 99 Decision**: Concept documented, implementation deferred
---
### Implementation Priority (Future)
**Phase 100-101 Focus**: User-facing migrations (console_println!)
**Phase 102+ Candidates**:
1. Error log consolidation (HIGH impact)
2. Internal state logging (MEDIUM impact)
3. Execution tracing (LOW impact, high cost)
**Decision Point**: After console_println! migration is complete
---
## Section 4: Call Site Distribution
### By Module (Approximate)
**src/runner/**: ~366 locations
- Priority: HIGH (user-facing)
- Target: console_println!
**src/mir/**: ~200 locations
- Priority: MEDIUM (internal/debug)
- Target: Ring0.log or removal
**src/parser/**: ~150 locations
- Priority: MEDIUM (internal/debug)
- Target: Ring0.log or removal
**tests/**: ~299 locations
- Priority: LOW (keep as-is)
- Target: None
**Other**: ~761 locations
- Priority: TBD
- Target: TBD
---
### By Type (Approximate)
**Error messages**: ~400 locations
- User errors → console_println!
- Internal errors → Ring0.log.error
**Debug output**: ~600 locations
- Development debug → Ring0.log.debug or removal
- Temporary debug → removal
**Progress/info**: ~200 locations
- User progress → console_println!
- Internal progress → Ring0.log.info
**Test output**: ~299 locations
- Keep as-is
**Other**: ~277 locations
- TBD
---
## Section 5: Migration Roadmap
### Phase 99 (Current): Documentation & Planning
**Objectives**:
- ✅ Document Ring0.log infrastructure
- ✅ Categorize remaining println!/eprintln! call sites
- ✅ Establish migration strategy
- ✅ Define completion criteria
**Deliverables**:
- This document (ring0-inventory.md)
- Logging policy (logging_policy.md)
- Updated core_boxes_design.md Section 15.6-A
---
### Phase 100-101: User-Facing Migrations
**Objectives**:
- Migrate ~366 user-facing println! to console_println!
- Focus on src/runner/ paths
- Ensure all CLI messages use ConsoleService
**Estimated Effort**: Medium (straightforward replacements)
**Success Criteria**:
- All user-visible messages use console_println!
- No println! in main execution paths
- Tests still pass
---
### Phase 102+: Internal Logging
**Objectives**:
- Evaluate Ring0.log usage for internal logging
- Migrate or remove dev-debug println!
- Consolidate error logging
**Estimated Effort**: Variable (requires case-by-case analysis)
**Success Criteria**:
- Clear separation: Ring0.log (internal) vs ConsoleService (user)
- No unnecessary println! in production code
- Test println! remains untouched
---
## Section 6: Grep Commands for Investigation
### Finding Call Sites
```bash
# All println!/eprintln! in source code
rg 'println!|eprintln!' --type rust
# Excluding tests
rg 'println!|eprintln!' --type rust --glob '!**/tests/**' --glob '!**/test_*.rs'
# Only in src/runner/
rg 'println!|eprintln!' --type rust src/runner/
# Only in src/mir/
rg 'println!|eprintln!' --type rust src/mir/
# Only in tests
rg 'println!|eprintln!' --type rust --glob '**/tests/**' --glob '**/test_*.rs'
```
---
### Finding console_println! Usage
```bash
# Current console_println! usage
rg 'console_println!' --type rust
# Potential candidates for console_println!
rg 'eprintln!\("Error:|Warning:|Info:' --type rust
```
---
### Finding Ring0.log Usage
```bash
# Current Ring0.log usage
rg 'ring0\.log\.(debug|info|warn|error)' --type rust
# LogApi trait implementations
rg 'impl.*LogApi' --type rust
```
---
## Section 7: Historical Migration Data (Phase 88-90)
### Phase 88-90: ring0.log.* Migration (56 locations)
**Migrated Files**:
- `src/runner/selfhost.rs`: 11 locations
- `src/runner/modes/vm.rs`: 22 locations
- `src/runner/modes/vm_fallback.rs`: 4 locations
- `src/runner/modes/common_util/hack_check.rs`: 19 locations
**Impact**: Consolidated user-facing error messages to Ring0.log.error()
---
### Phase 90: Ring0 API Migration (12 locations)
**Phase 90-A: fs API (7 locations)**:
- `src/runner/modes/common_util/resolve/strip.rs`: 4 locations
- `src/runner/dispatch.rs`: 1 location
- `src/runner/mod.rs`: 3 locations
- Migration: `std::fs::read_to_string``ring0.fs.read_to_string`
**Phase 90-C: time API (3 locations)**:
- `src/runner/modes/common_util/selfhost_exe.rs`: 1 location
- `src/runner/modes/common_util/io.rs`: 1 location
- `src/runtime/plugin_loader_unified.rs`: 1 location
- Migration: `Instant::now() + elapsed()``ring0.time.monotonic_now() + ring0.time.elapsed()`
**Phase 90-D: thread API (2 locations)**:
- `src/runtime/global_hooks.rs`: 1 location
- `src/runtime/plugin_loader_unified.rs`: 1 location
- Migration: `std::thread::sleep``ring0.thread.sleep`
---
## Section 8: Success Metrics
### Completion Criteria
**Phase 99 Complete** when:
- ✅ Ring0.log infrastructure documented
- ✅ println!/eprintln! call sites categorized
- ✅ Migration strategy established
- ✅ Roadmap defined for Phase 100+
**Phase 100-101 Complete** when:
- All user-facing println! migrated to console_println!
- src/runner/ paths use ConsoleService exclusively
- Test println! remains untouched
**Phase 102+ Complete** when:
- Internal logging uses Ring0.log appropriately
- No unnecessary println! in production code
- Clear separation of concerns maintained
---
## Related Documentation
- [Logging Policy](logging_policy.md) - Role separation and macro policy
- [CoreBoxes Design - Section 15.6-A](core_boxes_design.md#section-156-a-logsoutput-unified-design) - Architectural context
- [Phase 85 CURRENT_TASK](../../../CURRENT_TASK.md) - Implementation timeline
---
## Summary
Phase 99 establishes a **clear inventory** of logging infrastructure and println! call sites:
1. **Ring0.log**: Underutilized, ready for expansion
2. **println!/eprintln!**: 1477 production call sites categorized into 4 groups
3. **Migration strategy**: Phased approach starting with user-facing messages
4. **Success criteria**: Clear metrics for each phase
**Next Steps**: Phase 100+ will implement gradual migrations based on this inventory.