utf8-forge 0.1.0

A focused, idempotent, bidirectional charset transcoder for source trees. Default output: UTF-8 without BOM.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
# EXECUTION.md — utf8-forge Rollout Playbook

> **Target**: `D:\server` multi-solution Windows C++ game server.
> **Aligned with**: Playbook P0–P4 (*Source UTF-8 Unification & Cross-Platform Charset*).
> **Scope**: Source → UTF-8 without BOM only. `/utf-8` flag, rebuild, and smoke tests are covered in the original
> Playbook §2–§3.

---

## 0. Five-Minute Version

```bash
cargo build --release

./target/release/utf8-forge scan    --root D:\server --report D:\tmp\scan.json
./target/release/utf8-forge convert --root D:\server --dry-run --report D:\tmp\dry.json
./target/release/utf8-forge convert --root D:\server --backup-dir D:\backup\utf8-forge
./target/release/utf8-forge verify  --root D:\server
```

**If any step reports `Unknown` or `DecodeError`, stop and read §6.**

---

## 1. Prerequisites

| Item        | Requirement                                                       |
|-------------|-------------------------------------------------------------------|
| OS          | Windows 10/11 (tool is cross-platform; rollout target is Windows) |
| Rust        | **≥ 1.85** (edition 2024)                                         |
| SVN         | Working copy **clean**; coordinate a "transcode window"           |
| Disk        | Space for backup (≈ source tree size)                             |
| Permissions | Read/write on `D:\server`                                         |
| IDE         | Close auto-save on the target directory                           |

```bat
cd D:\server
svn status      :: must be empty
svn info        :: record revision
```

---

## 2. Build & Install

```bash
# In-tree
cd utf8-forge
cargo build --release
# Binary: target\release\utf8-forge.exe

# Or install to PATH
cargo install --path . --locked
```

**Smoke**:

```bash
utf8-forge --version
utf8-forge scan --help
```

> If you enabled only default features, `reqwest` is compiled in. To build a **local-only** binary:
> ```bash
> cargo build --release --no-default-features
> ```

---

## 3. Execution Flow (P0 → P1)

### 3.1 P0 — Inventory & Freeze

```bat
utf8-forge scan ^
  --root D:\server ^
  --report D:\backup\utf8-forge\scan-before.json ^
  --verbose
```

**Expected summary** (order of magnitude):

```json
{
  "summary": {
    "total_files": 1247,
    "utf8": 1035,
    "utf8_bom": 34,
    "utf16le": 2,
    "gb18030": 171,
    "unknown": 5
  }
}
```

**Check**:

- `gb18030` ≈ 97 (Playbook §1.2);
- `utf16le` ≈ 2 (`GameServer/room/FieldData.cpp` × 2);
- Every `unknown` is **manually confirmed**.

**Exit criteria**: report archived; team notified; unknown files triaged.

---

### 3.2 P1 — Transcode

#### 3.2.1 Dry-Run First

```bat
utf8-forge convert ^
  --root D:\server ^
  --dry-run ^
  --report D:\backup\utf8-forge\dry.json ^
  --verbose
```

**Audit `dry.json`**:

| Check                                      | Expected                           |
|--------------------------------------------|------------------------------------|
| `action == "would_convert"`                | Only expected paths                |
| `dep/`, `_tools/`, `temp/`, `OutputFile*/` | **Absent**                         |
| `.png/.zip/.exe/.lib/.dll`                 | **Absent**                         |
| `.rc`                                      | Absent (unless `--include-rc`)     |
| Any file > 200 MiB                         | None (or adjust `--max-file-size`) |

**Stop immediately if anything unexpected appears.** Adjust `--exclude` / `--ext` and re-run dry-run.

#### 3.2.2 Real Conversion

```bat
utf8-forge convert ^
  --root D:\server ^
  --backup-dir D:\backup\utf8-forge\orig ^
  --report D:\backup\utf8-forge\apply.json ^
  --verbose
```

**Guarantees**:

- **Atomic writes** — power loss never corrupts source.
- **Only changed files written** — `already_utf8` untouched (no mtime churn).
- **Per-file error isolation** — one failure does not abort the batch.
- **Replayable backup** — original bytes preserved under mirrored path.

**Output**:

```text
[utf8-forge] mode=convert target=utf-8 root=D:\server
[utf8-forge] scanned=1247  candidates=1142
[utf8-forge] already_utf8=1035  converted=171  unknown=5  errors=0
[utf8-forge] duration=8.3s  report=D:\backup\utf8-forge\apply.json
```

#### 3.2.3 Immediate Verification

```bat
utf8-forge verify --root D:\server --report D:\backup\utf8-forge\verify1.json
```

- **Exit 0** + `all_utf8=true` → pass.
- **Exit 3** → list contains unexpected files; investigate each.

> If `unknown > 0`, `verify` will return 3 because those files remain non-UTF-8. This is **expected**; triage per §6.

#### 3.2.4 Idempotence Self-Check

```bat
utf8-forge convert --root D:\server --report D:\backup\utf8-forge\apply2.json
```

**Expected**: `converted=0`. If not, stop — check `apply.json` vs `apply2.json` diff for concurrent edits.

---

### 3.3 P1 Exit Criteria

- [ ] First `convert` `converted` matches dry-run prediction.
- [ ] Second `convert` `converted == 0` (idempotent).
- [ ] `verify` exit 0 (or only known unknowns).
- [ ] SVN diff contains only expected files (§4).
- [ ] Backup directory complete and replayable.

---

### 3.4 P2 — Global `/utf-8` (Tool Does Not Participate)

```text
Per Playbook §2.2:
1. Add /utf-8 to every production .vcxproj ClCompile section.
2. Remove 3 per-file /utf-8 exceptions in GameServer.vcxproj.
3. Clean Rebuild.
```

**Precondition**: `verify` passed (source 100% UTF-8). Otherwise **do not** enable `/utf-8` — it will cause
double-mojibake.

> Optional: if `.vcxproj/.sln` should also be unified, use
> `utf8-forge convert --root D:\server --include-msbuild`.
> VS2019 may re-save with BOM — harmless.

---

### 3.5 P3 — Rebuild & Smoke (Playbook §6.3)

```text
Follow Playbook §7 checklist. This tool provides only the encoding evidence:
- [x] verify passes
- [ ] Clean Rebuild passes
- [ ] Chinese logs readable
- [ ] Chinese protocol/DB regression
- [ ] genbin Chinese export correct
```

---

### 3.6 P4 — CI / Pre-Commit Hardening

```bat
:: pre-commit hook (Windows batch sketch)
utf8-forge verify --root %CD% --ext %CHANGED_EXTS% || exit /b 1
```

```yaml
# Generic CI step
- name: Verify encoding
  run: utf8-forge verify --root . --report encoding-report.json
```

Also commit `.editorconfig`:

```ini
root = true
[*.{c,cc,cpp,h,hpp,inl,proto}]
charset = utf-8
end_of_line = crlf
insert_final_newline = true
```

---

## 4. SVN Collaboration & Diff Audit

### 4.1 Before

```bat
cd D:\server
svn status > D:\backup\utf8-forge\before-status.txt
```

### 4.2 After

```bat
svn status > D:\backup\utf8-forge\after-status.txt
svn diff --summarize > D:\backup\utf8-forge\summary.txt
```

**Must satisfy**:

- Every path in `summary.txt` ∈ `files[].path` from `apply.json`.
- No `dep/`, `_tools/`, `temp/`, `OutputFile*/`.
- No binary extensions.
- Commit per logical directory in a single window to avoid mixed GBK/UTF-8 intermediate states.

### 4.3 Diff Review

- Every line changing is **normal** (encoding change → byte change → SVN sees whole-line diff).
- Focus on: Chinese comments readable, narrow-string literals consistent.
- Spot-check (Playbook §6.1 P1 list):
    - `GameServer/Channel.cpp`
    - `GameServer/GameProcess.cpp`
    - `Share/common/String.h`
    - `GameServer/room/FieldData.cpp` (original UTF-16)
    - `genbin/genbin.cpp`

---

## 5. Recipes (v0.2)

### 5.1 C/C++ + proto/txt Only

```bat
utf8-forge convert ^
  --root D:\server ^
  --ext h,hpp,c,cpp,cc,inl,proto,txt ^
  --backup-dir D:\backup\utf8-forge\orig
```

### 5.2 Include MSBuild Files

```bat
utf8-forge convert ^
  --root D:\server ^
  --include-msbuild ^
  --backup-dir D:\backup\utf8-forge\orig
```

### 5.3 Extra Exclusions

```bat
utf8-forge scan ^
  --root D:\server ^
  --exclude "GameServer201,Test_Client" ^
  --exclude-glob "**/Generated/**"
```

### 5.4 Scan Only (for Review)

```bat
utf8-forge scan --root D:\server --report scan.json -q
```

### 5.5 Remote Download & Transcode

```bat
:: Fetch a GBK-encoded file from an HTTP endpoint and save as UTF-8
utf8-forge convert ^
  --url https://example.com/data/legacy_server.cpp ^
  --output D:\server\external\legacy_server.cpp ^
  --target utf-8 ^
  --report D:\backup\utf8-forge\fetch-report.json
```

**Notes**:

- `--output` omitted → filename derived from URL last segment + `.utf8`.
- `--max-file-size` applies to the remote download too.
- `--dry-run` works with `--url`: fetches and reports, but does not write.

### 5.6 Reverse: UTF-8 → GB18030 (Legacy Scripts Only)

```bat
utf8-forge convert ^
  --root D:\server\legacy\scripts ^
  --target gb18030 ^
  --ext bat,cmd ^
  --backup-dir D:\backup\utf8-forge\orig-gbk
```

> ⚠️ Do not use unless a legacy external dependency requires GBK.

---

## 6. Unknown / DecodeError Handling

| Report Category | Meaning                         | Action                                            |
|-----------------|---------------------------------|---------------------------------------------------|
| `unknown`       | Not UTF-8 / UTF-16 / GB18030    | Inspect hex; often a binary with a text extension |
| `decode_error`  | Legal encoding, truncated bytes | Hex editor; ask original author                   |
| `too_large`     | > `--max-file-size`             | Usually skip; raise limit only if necessary       |
| `io_error`      | Permission / locked file        | Close the locking process or fix ACLs             |
| `fetch_error`   | `--url` network/TLS failure     | Check URL, proxy, timeout                         |

**Principles**:

1. **Never guess.** The tool does not guess; humans must not either.
2. Unknown files are preserved verbatim and committed **separately**.
3. If a file is truly a BOM-less UTF-16 (rare), add BOM manually and re-run `convert`.
4. If a binary was misnamed as `.cpp`, exclude it from the whitelist.

---

## 7. Rollback

### 7.1 Single File (from backup)

```bat
copy /Y D:\backup\utf8-forge\orig\D\server\GameServer\Channel.cpp D:\server\GameServer\Channel.cpp
```

### 7.2 Full SVN Rollback

```bat
cd D:\server
svn revert -R .
svn status             :: must be empty
```

> If already committed: `svn merge -c -<rev> .`

### 7.3 Post-Rollback

- Re-run `utf8-forge scan` to confirm baseline.
- Notify the team; pause P2.

---

## 8. Playbook Mapping (v0.2)

| Playbook Phase         | This Manual              | Tool Command                       |
|------------------------|--------------------------|------------------------------------|
| P0 Inventory & Freeze  | §3.1                     | `scan --report`                    |
| P1 Source Transcode    | §3.2                     | `convert [--dry-run] --backup-dir` |
| P1 Exit Criteria       | §3.3                     | `verify` + idempotence check       |
| P2 Global `/utf-8`     | §3.4 (tool not involved) | —                                  |
| P3 Rebuild & Smoke     | §3.5                     | `verify` as evidence               |
| P4 CI Hardening        | §3.6                     | `verify` in pre-commit/CI          |
| Optional Remote Source | §5.5                     | `convert --url ... --output ...`   |

---

## 9. Risks & Mitigations (Playbook §2.4)

| Risk                                 | Mitigation                                        |
|--------------------------------------|---------------------------------------------------|
| Incomplete transcode before `/utf-8` | `verify` exit 0 as P2 gate                        |
| Console mojibake (narrow strings)    | P3 smoke scope; tool only guarantees source bytes |
| PCH / incremental stale objects      | Clean Rebuild in P3                               |
| Accidental `dep/` modification       | Default blacklist + dry-run audit                 |
| Large SVN diff / partial commit      | Single window + `svn diff --summarize`            |
| Runtime protocol/DB regression       | Boundaries already UTF-8; regression tests cover  |
| Remote fetch hangs                   | `--max-file-size` + 120 s timeout                 |

---

## 10. Acceptance Checklist (Printable)

### Before

- [ ] `svn status` empty
- [ ] Transcode window announced
- [ ] `scan.json` archived and reviewed
- [ ] `dry.json` reviewed; path list clean
- [ ] Backup directory writable with sufficient space

### During

- [ ] First `convert` `converted` = dry-run prediction
- [ ] `apply.json` has no `error` entries
- [ ] `unknown` list generated and assigned

### After

- [ ] `verify` exit 0 (or only known unknowns)
- [ ] Second `convert` `changed = 0`
- [ ] `svn diff --summarize` only expected files
- [ ] Spot-check: 5 representative Chinese-comment files readable
- [ ] Backup complete and replayable

### P2 / P3 Hand-off

- [ ] `/utf-8` added per Playbook §2.2
- [ ] Per-file `/utf-8` exceptions removed
- [ ] Clean Rebuild passes
- [ ] Smoke tests pass (Playbook §7)

---

## 11. Troubleshooting

| Symptom                          | Check                                             | Fix                                           |
|----------------------------------|---------------------------------------------------|-----------------------------------------------|
| Files not converted              | `-v`; check whitelist, excluded dirs, hidden flag | Adjust `--ext` / `--include-hidden`           |
| `verify` exit 3                  | Read report for non-UTF-8 files                   | If `unknown`, §6; if missed, re-run `convert` |
| Chinese comments became mojibake | Likely double-transcode or wrong target           | `svn diff`; roll back single file             |
| Unexpected dirs in `svn diff`    | Dry-run skipped or ignored                        | Roll back; re-run dry-run                     |
| Very slow conversion             | Large files included                              | Lower `--max-file-size`; tune `--threads`     |
| Huge backup directory            | Backup uses original bytes                        | Keep ≥ 1 version cycle; prune later           |
| `--url` returns 403/404          | Server-side auth / path                           | Verify URL; use a direct download link        |
| `--url` memory spike             | File > `--max-file-size`                          | Raise limit cautiously or split file          |

---

## 12. Appendix: JSON Report Schema (v0.2)

```jsonc
{
  "tool": "utf8-forge",
  "version": "0.2.0",
  "mode": "convert",                     // scan | convert | verify | fetch
  "root": "D:\\server",
  "url": null,                           // populated when --url used
  "started_at": "2026-...",
  "duration_ms": 8300,
  "options": {
    "target": "utf-8",
    "dry_run": false,
    "extensions": ["h","hpp","c","cpp"],
    "exclude_dirs": ["dep","_tools"],
    "backup_dir": "D:\\backup\\utf8-forge\\orig"
  },
  "summary": {
    "total_files": 1247,
    "candidates": 1142,
    "already_utf8": 1035,
    "converted": 171,
    "unknown": 5,
    "decode_errors": 0,
    "io_errors": 0,
    "too_large": 0,
    "fetch_error": 0
  },
  "files": [
    {
      "path": "D:\\server\\GameServer\\Channel.cpp",
      "detected": "gb18030",
      "action": "converted",             // would_convert | converted | unchanged | skipped_unknown | error
      "bytes_before": 12873,
      "bytes_after": 15201,
      "duration_us": 912
    }
  ],
  "unknown_files": [],
  "error_files": []
}
```

Field semantics map 1:1 to `DESIGN.md §9`.