utf8-forge 0.1.0

A focused, idempotent, bidirectional charset transcoder for source trees. Default output: UTF-8 without BOM.
Documentation
# AGENT.md — utf8-forge Maintenance Guide

> **Audience**: AI agents and new maintainers.
> **Goal**: Understand, extend, and safely modify `utf8-forge` without breaking invariants.

---

## 1. What This Tool Is

`utf8-forge` is a **small, focused Rust CLI** that:

- Unifies **mixed-encoding source trees** to **UTF-8 without BOM** (default).
- Supports **bidirectional** conversion (`→ utf-8-bom / gb18030 / utf-16le / utf-16be`).
- Optionally **fetches a remote file** (`--url`) and transcodes it in one step.
- Aligns with **P1 (Source Transcoding)** of the *Source UTF-8 Unification Playbook*.

**It does not**: compile, run tests, touch SVN/Git, process binaries, or modify `dep/`.

---

## 2. 30-Second Quick Start

```bash
# Build
cargo build --release

# 1) Scan distribution
./target/release/utf8-forge scan --root D:\server --report scan.json

# 2) Dry-run
./target/release/utf8-forge convert --root D:\server --dry-run --report dry.json

# 3) Convert with backup
./target/release/utf8-forge convert --root D:\server --backup-dir D:\backup\utf8-forge

# 4) Verify
./target/release/utf8-forge verify --root D:\server
```

**Safety rule**: `scan` → `--dry-run` → `convert`. Never skip step 2.

---

## 3. Commands (v0.2)

| Command         | Purpose                                       |         Writes?         | Exit codes              |
|-----------------|-----------------------------------------------|:-----------------------:|-------------------------|
| `scan`          | Detect only; distribution report              |           ❌            | 0 / 1 (Unknown present) |
| `convert`       | Detect + transcode + atomic write             | ✅ (unless `--dry-run`) | 0 / 1                   |
| `convert --url` | Fetch → transcode → save                      |           ✅            | 0 / 1                   |
| `verify`        | Assert all whitelisted files are UTF-8 no BOM |           ❌            | 0 / 3                   |

---

## 4. Core Options

| Option              | Default         | Notes                                          |
|---------------------|-----------------|------------------------------------------------|
| `-r, --root`        | `.`             | Recursive                                      |
| `-e, --ext`         | See DESIGN §5.1 | **Overrides** default whitelist                |
| `-X, --exclude-ext` | empty           | Appended                                       |
| `-x, --exclude`     | See DESIGN §5.2 | Appended                                       |
| `--include-rc`      | false           | Adds `.rc/.rc2/.dlg`                           |
| `--include-msbuild` | false           | Adds `.sln/.vcxproj/...`                       |
| `--include-hidden`  | false           | Processes dot-files                            |
| `-t, --target`      | `utf-8`         | `utf-8-bom`, `gb18030`, `utf-16le`, `utf-16be` |
| `--dry-run`         | false           | No writes                                      |
| `--backup-dir`      | none            | Original bytes preserved                       |
| `--max-file-size`   | 200 MiB         | Above → `too_large`                            |
| `--threads`         | CPU count       | Rayon pool size                                |
| `--report`          | none            | JSON report path                               |
| `--url`             | none            | **Remote fetch (convert only)**                |
| `--output`          | derived         | Destination for `--url`                        |

**Conflict**: `--include-rc` + `--exclude-ext rc` → fatal (exit 2).

---

## 5. Source Layout & English Comment Policy

```
src/
├── main.rs       # Entry point
├── cli.rs        # clap derive; all flags documented with /// English
├── detector.rs   # Encoding sniffing; see DESIGN §3
├── transcoder.rs # Strict decode / encode; see DESIGN §4
├── filter.rs     # Whitelist + blacklist; see DESIGN §5
├── walker.rs     # walkdir wrapper
├── writer.rs     # Atomic write; see DESIGN §7
├── fetcher.rs    # Optional remote download; see DESIGN §8
├── reporter.rs   # Console + JSON
└── error.rs      # anyhow-based errors
```

**Rule**: Every `pub fn`, `pub struct`, and non-obvious `fn` carries a `///` doc comment in **English**. Internal tricky
blocks use `// English explanation.` No Chinese in `src/`.

---

## 6. Key Invariants (Must Read Before Coding)

| #  | Invariant                                | Consequence of Violation          |
|----|------------------------------------------|-----------------------------------|
| 1  | Default output = UTF-8 **no BOM**        | Breaks Playbook Strategy A        |
| 2  | UTF-16 encoders **manually prepend BOM** | Output unreadable                 |
| 3  | No newline normalization                 | Diff noise                        |
| 4  | Whitelist + blacklist double gate        | `dep/` or `.exe` corruption       |
| 5  | Byte-identical → no write                | mtime churn / SVN false positives |
| 6  | Temp file + rename                       | Source loss on power failure      |
| 7  | `had_errors == true` → hard error        | Half-written mojibake             |
| 8  | Report sorted by path                    | Non-reproducible audits           |
| 9  | No symlink recursion                     | Infinite loop                     |
| 10 | Second `convert` = 0 changes             | Idempotence regression            |

**Do not modify the code unless you can keep all 10 true.**

---

## 7. How to Extend

### 7.1 Add a Language Extension

Edit `src/filter.rs::DEFAULT_EXTENSIONS`; update `DESIGN.md §5.1`; add an integration test that places a `.xyz` file and
asserts `scan` recognizes it.

### 7.2 Add an Excluded Directory

Edit `DEFAULT_EXCLUDE_DIRS` or `DEFAULT_EXCLUDE_PREFIXES` in `src/filter.rs`. **Never** hard-code names in `walker.rs`.

### 7.3 Add a Target Encoding

1. Extend `TargetEncoding` enum in `transcoder.rs`.
2. Add alias in `parse()`.
3. Implement in `encode()` — **remember BOM if stateful**.
4. If round-trip detection is needed, extend `DetectedEncoding` and `detect()`.
5. Update `DESIGN.md §2`.
6. Add round-trip test (`A→B→A == A`) in `tests/transcode.rs`.

### 7.4 Modify Remote Fetch Behaviour

`src/fetcher.rs` is isolated. Changes there **must not** affect `detect()` / `transcode()` / `writer::atomic_write`.
Follow the streaming/buffering split in `DESIGN §8.3`.

### 7.5 Add a New Subcommand

1. Add variant in `cli.rs::Subcommand`.
2. Match in `main.rs`.
3. Reuse `walker::collect_files` and `filter::*` — do not duplicate traversal logic.
4. New write commands **must** support `--dry-run` and `atomic_write`.

---

## 8. Code Quality Gates

- `cargo fmt --check`
- `cargo clippy --all-targets -- -D warnings`
- `cargo test` (unit + integration)
- **No `unwrap()` / `expect()`** in non-test code. Use `anyhow::Result`.
- English comments only in `src/`. Chinese belongs in `README.zh-CN.md` / `docs/USAGE.zh-CN.md`.

---

## 9. Troubleshooting Cheat Sheet

| Symptom                        | Check                                                                |
|--------------------------------|----------------------------------------------------------------------|
| Files skipped unexpectedly     | `-v`; verify extension, excluded dir, hidden flag, `--max-file-size` |
| High `Unknown` count           | Real binaries with wrong extension — inspect with hex editor         |
| `DecodeError`                  | Truncated byte sequences; do **not** change heuristics               |
| Second `convert` changes files | Violation of invariant #5 or #10                                     |
| `verify` exit 3                | Non-UTF-8 whitelisted files; `-v` lists them                         |
| `--url` fetch fails            | Check timeout, TLS, `Content-Length` vs `--max-file-size`            |
| VS re-adds BOM to `.vcxproj`   | Normal; MSBuild editor behaviour, not a tool bug                     |

---

## 10. Mapping to Playbook P0–P4

| Playbook Phase   | Tool Role                    |
|------------------|------------------------------|
| P0 Inventory     | `scan --report`              |
| P1 Transcoding   | `convert` (main battlefield) |
| P2 `/utf-8` flag | ❌ Not this tool             |
| P3 Rebuild       | `verify` as gate             |
| P4 CI            | `verify` in pre-commit / CI  |

See `EXECUTION.md` for concrete steps.

---

## 11. Documentation Files

| File                  | Language              | Purpose                        |
|-----------------------|-----------------------|--------------------------------|
| `README.md`           | **English (default)** | Overview, install, quick start |
| `README.zh-CN.md`     | Chinese               | Same content, localized        |
| `docs/USAGE.md`       | **English**           | Full CLI reference, recipes    |
| `docs/USAGE.zh-CN.md` | Chinese               | Same content, localized        |
| `DESIGN.md`           | English               | Architecture & invariants      |
| `AGENT.md`            | English               | This file                      |
| `EXECUTION.md`        | English               | `D:\server` rollout playbook   |

---

*AGENT.md v0.2 — The 10 invariants in §6 are non-negotiable.*