trox 0.2.1

Immutable source-authored localization values and deterministic bundle runtime
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
# Trox

Trox is a source-extraction localization system for Rust, TypeScript/TSX, and
static RON data. Developers write complete English messages beside their use
sites; Trox extracts them, expands locale-specific grammar into flat CSV rows,
and builds deterministic bundles for Rust and TypeScript runtimes. Messages
remain immutable, locale-independent `LocalizedString` values until an
explicit `Localizer` renders them at the presentation boundary, avoiding text
fragments, translator-authored programs, implicit locale state, and runtime
morphology.

Here is a Rust message with interpolation, exact-zero wording, and cardinal
plural selection:

```rust
use trox::prelude::*;

fn cards_remaining(card_count: u32) -> LocalizedString {
    txa(
        plural(card_count, [
            exact(0, "No cards remain."),
            one("{card_count} card remains."),
            other("{card_count} cards remain."),
        ]),
        tx_args![card_count],
        "Status text showing how many cards remain in the deck.",
    )
}

let value = cards_remaining(3);
let localizer = Localizer::for_source(SourceLocale::new("en-US")?)?;
let text = localizer.resolve(&value);
assert_eq!(text, "\u{2068}3\u{2069} cards remain.");
# Ok::<(), Box<dyn std::error::Error>>(())
```

## Install and start

Trox requires Rust 1.89 or newer. Add the runtime library to an application:

```sh
cargo add trox
```

Create a `trox.ron` at the project root:

```ron
(
    source_locale: "en-US",
    terms: "terms.ron",
    source_bundle: ".trox-output/en-US.trox.json",
    source_report: ".trox-output/en-US.csv",
    sources: [(language: Rust, include: ["src/**/*.rs"])],
    locales: {},
    term_forms: {},
)
```

Create an empty `terms.ron` containing `{}` and ignore the disposable output
directory:

```gitignore
/.trox-output/
```

Construct the development localizer from those two human-authored files. Using
`include_str!` is convenient, but applications may load the bytes however they
choose:

```rust
use trox::prelude::*;

fn source_localizer() -> Result<Localizer, Box<dyn std::error::Error>> {
    let source = SourceLocale::from_project_ron(
        include_str!("../trox.ron"),
        include_str!("../terms.ron"),
    )?;
    Ok(Localizer::for_source(source)?)
}
```

`cargo check`, `cargo test`, `cargo clippy`, and `cargo run` now need only the
application source, `trox.ron`, and `terms.ron`. Changing a `tx` or `txa` call
changes the rendered source text on the next build; there is no extraction or
bundle-generation step in the Rust build.

Install `trox-cli` separately only when extracting translator material or
building release bundles:

```sh
cargo install trox-cli
trox check --deny warnings
trox extract
trox release-check
```

The package installs a binary named `trox`. Its Rust modules are implementation
details of the executable and are not a supported library API. Add a locale's
profile, CSV, and bundle paths to `trox.ron`, then create its initial files with
`trox locale init LOCALE`. The full configuration contract is documented under
[Project configuration](#project-configuration).

## Support policy

- `trox` and `trox-cli` support Rust 1.89 and newer.
- The Rust runtime is tested on Linux, macOS, and Windows.
- The `trox` command is tested on Linux, macOS, and Windows. On non-Unix
  platforms its optional benchmark reports no peak-memory measurement.
- The `trox` library follows Cargo semantic versioning. The `trox-cli` package
  exposes only the `trox` executable; its internal Rust modules are not API.
- Bundle and serialized-value compatibility is versioned explicitly by their
  embedded format versions and validated when data is loaded.

## Capabilities and boundaries

Trox provides:

- Inline complete English messages.
- Named placeholders in Rust and TypeScript.
- Exact, cardinal, ordinal, and semantic selection.
- RON message and typed-template extraction.
- Locale-specific row expansion.
- Non-destructive CSV synchronization.
- Deterministic JSON bundles.
- Compatible Rust and TypeScript runtimes.
- Canonical serialization of unresolved messages.
- Visible source fallback with diagnostics.

Trox does not provide:

- String-fragment composition.
- Translator-authored selector syntax.
- A general expression language.
- Automatic articles, case, or morphology.
- Arbitrary nested localized messages.
- Implicit global locale discovery.
- Runtime filesystem or network access.
- Currency, date, unit, or list formatting.
- Interpreted HTML or rich-text markup.

Design rules:

- Every selector leaf is a complete message.
- Translation files contain text, not programs.
- Terms are sparse, shallow, and explicit.
- Application code owns semantic inputs.
- Locale profiles own locale-private grammar.
- Deterministic tooling is authoritative.

## Repository

```text
.
├── crates/
│   ├── trox/          Rust API, bundles, wire values, resolver
│   └── trox-cli/      `trox` binary, scanners, CSV workflow, bundle builder
├── packages/
│   └── trox/          `@trox/runtime` TypeScript package
├── crates/trox/tests/fixtures/
│   └── conformance/   canonical cross-language fixtures
├── crates/trox-cli/tests/fixtures/
│   └── quest/         multilingual scenario corpus
├── Cargo.toml         Rust workspace
├── package.json       npm workspace
└── README.md          project documentation
```

Build and test:

```sh
cargo test --workspace
npm install
npm run typecheck
npm test
npm run build
```

Run the Quest workflow:

```sh
cargo run --release -p trox-cli --bin trox -- \
  --config crates/trox-cli/tests/fixtures/quest/trox.ron extract

cargo run --release -p trox-cli --bin trox -- \
  --config crates/trox-cli/tests/fixtures/quest/trox.ron check

cargo run --release -p trox-cli --bin trox -- \
  --config crates/trox-cli/tests/fixtures/quest/trox.ron bundle --allow-missing
```

Typical application workflow:

1. Add `tx` or `txa` calls to Rust or TypeScript.
2. Add flat `Tx(...)` records to configured RON data.
3. Declare runtime grammatical terms only when needed.
4. Use `Localizer::for_source` for normal builds, tests, and local runs.
5. Configure ignored localization outputs in `trox.ron`.
6. Run `trox check` without requiring any generated output to exist.
7. Run `trox extract` in localization automation and hand off its CSV/workbook.
8. Translate the generated rows outside the application source checkout.
9. Run `trox release-check` in localization or packaging automation.
10. Load the generated source and target bundles in production.
11. Resolve messages only at the presentation boundary.

## Source-development localization

`Localizer::for_source` deliberately does not look up message entries or rows.
It selects directly from the live `LocalizedString` identity, then applies the
source locale's pinned cardinal rules, ordinal rules, decimal formatting, text
direction, isolation policy, and term surfaces. Checked and recovering
resolution APIs are both available, but ordinary source messages never produce
missing-message or missing-row diagnostics.

`SourceLocale::new("en-US")` is sufficient when the application has no terms.
`SourceLocale::from_project_ron` additionally reads the existing source locale,
term-form declarations, source fallback policy, term values, numbered forms,
and optional source term facets from human-authored RON. It does not scan Rust,
TypeScript, or RON message sources and it does not read the filesystem.

Source mode is for in-process values authored by the application. Canonical
wire decoding still requires a generated `SourceCatalog` because accepting a
self-consistent message hash is not an authorization boundary.

## Rust syntax

Use the prelude in ordinary authoring modules:

```rust
use trox::prelude::*;
```

It exports:

- `LocalizedString`, `Localizer`, and `TermId`.
- `tx`, `txa`, `meaning`, `ls`, and `tx_args!`.
- `plural`, `ordinal`, and `select`.
- `exact`, `zero`, `one`, `two`, `few`, `many`, and `other`.
- `when`, `otherwise`, and `TroxSelector`.
- `term`, `indefinite`, `counted`, and `opaque`.

### Static text

Use `tx` when there are no visible placeholders:

```rust
fn close_label() -> LocalizedString {
    tx(
        "Close deck browser",
        "Accessible label that closes the deck browser.",
    )
}
```

The final argument is required translator context. The result is not a host
`String`:

```rust
let value: LocalizedString = close_label();
let text: String = localizer.resolve(&value);
```

### Intentionally untranslated text

Use `ls` when runtime text is intentionally safe to display without
translation:

```rust
fn player_name(raw_string: &str) -> LocalizedString {
    ls(raw_string)
}
```

Appropriate uses are:

- Migrations, while existing text is being moved behind `LocalizedString` APIs.
- Raw user input that must be displayed verbatim, such as a player name.
- Tests that need a lightweight `LocalizedString` value.
- Developer-only surfaces whose text is not translated.

Calling `ls` asserts that this text does not need translation at this call
site. Do not use it for ordinary user-facing product copy. The extractor
deliberately ignores these calls, and the value resolves to
the supplied text in every locale, including text containing braces. Replace
migration uses with `tx` or `txa` as localization work is completed.

### Interpolation

Use `txa` for visible placeholders:

```rust
fn deck_label(deck_name: &str) -> LocalizedString {
    txa(
        "Deck: {deck_name}",
        tx_args![deck_name],
        "Label followed by the user-defined deck name.",
    )
}
```

Bind multiple values or map a different expression:

```rust
fn progress(owned_count: u32, total_count: u32) -> LocalizedString {
    txa(
        "Collection: {owned_count}/{total_count}",
        tx_args![
            owned_count,
            total_count => total_count,
        ],
        "Owned cards followed by total available cards.",
    )
}
```

`tx_args!` evaluates each expression once and converts it into an owned Trox
value. It borrows ordinary input variables by default.

Placeholder names match:

```text
[a-z][a-z0-9]*(?:_[a-z0-9]+)*
```

Valid:

```text
{name}
{card_name}
{player_2_name}
```

Rejected:

```text
{0}
{CardName}
{cardName}
{card.name}
{card-name}
{cárd_name}
```

Rules:

- Names use lowercase ASCII snake case.
- Names are at most 64 ASCII bytes.
- Every visible placeholder has one binding.
- Every binding appears in at least one leaf.
- Target rows may move, repeat, or omit declared placeholders.
- Target rows cannot invent placeholders.
- `{{` and `}}` render literal braces.

```rust
tx(
    "Write {{card_name}} to show a placeholder.",
    "Help text showing placeholder notation.",
)
```

### Meaning

Disambiguate identical text with a semantic meaning key:

```rust
fn open_button() -> LocalizedString {
    tx(
        meaning("open-action", "Open"),
        "Button label that opens the selected deck.",
    )
}

fn open_state() -> LocalizedString {
    tx(
        meaning("open-state", "Open"),
        "Status adjective for a room accepting players.",
    )
}
```

The meaning key changes message identity. It is not an arbitrary developer
message ID. Extraction includes it at the start of the translator-facing
description as `Meaning: <key>`.

### Cardinal selection

Use `plural` for locale-dependent cardinal categories:

```rust
fn cards_remaining(card_count: u32) -> LocalizedString {
    txa(
        plural(card_count, [
            exact(0, "No cards remain."),
            one("{card_count} card remains."),
            other("{card_count} cards remain."),
        ]),
        tx_args![card_count],
        "Status text showing cards remaining in the deck.",
    )
}
```

Selection order:

1. Exact integer branch.
2. Target locale's CLDR category.
3. Matching category branch.
4. Required `other` branch.

Extraction adds target-only categories. A Russian CSV can receive `one`,
`few`, `many`, and `other` rows from an English source pattern.

The count need not be visible:

```rust
tx(
    plural(card_count, [
        one("A card remains."),
        other("Cards remain."),
    ]),
    "Status indicating whether one or multiple cards remain.",
)
```

### Ordinal selection

```rust
fn turn_position(turn_number: u32) -> LocalizedString {
    txa(
        ordinal(turn_number, [
            one("{turn_number}st turn"),
            two("{turn_number}nd turn"),
            few("{turn_number}rd turn"),
            other("{turn_number}th turn"),
        ]),
        tx_args![turn_number],
        "Label for a turn's ordinal position.",
    )
}
```

Plural and ordinal selectors accept nonnegative integers from zero through
`2^53 - 1`. Fractions, negative values, `NaN`, and infinities are invalid.

### Semantic selection

Define explicit stable keys:

```rust
#[derive(Clone, Copy, PartialEq, Eq)]
enum BattleZone {
    Deck,
    Hand,
    Void,
}

impl TroxSelector for BattleZone {
    fn trox_key(&self) -> &'static str {
        match self {
            Self::Deck => "deck",
            Self::Hand => "hand",
            Self::Void => "void",
        }
    }
}
```

Select complete messages:

```rust
fn search_zone(zone: BattleZone) -> LocalizedString {
    tx(
        select(zone, [
            when(BattleZone::Deck, "Search your deck."),
            when(BattleZone::Hand, "Search your hand."),
            when(BattleZone::Void, "Search your void."),
            otherwise("Search that zone."),
        ]),
        "Rules text directing the player to search a zone.",
    )
}
```

Rules:

- `otherwise` is mandatory.
- Keys are stable serialization contracts.
- Keys are unique within the selector.
- Keys use one uniform string or boolean type.
- Generic `select` is not a numeric plural operation.
- Ordinary application branching stays in ordinary control flow.

Nested selectors are supported. Every final leaf must still contain the full
sentence, including articles, verbs, and punctuation.

### Terms and atoms

Map domain values to explicit term IDs:

```rust
impl CardSubtype {
    fn term_id(self) -> TermId {
        match self {
            Self::Warrior => TermId::new("card-subtype.warrior"),
            Self::Relic => TermId::new("card-subtype.relic"),
            Self::Event => TermId::new("card-subtype.event"),
        }
    }
}
```

Request an indefinite form:

```rust
txa(
    "Change {card_name} to become {subtype}.",
    tx_args![
        card_name => opaque(card_name),
        subtype => indefinite(subtype.term_id()),
    ],
    "Card transformation with an indefinite subtype.",
)
```

`indefinite(id)` is shorthand for:

```rust
term(id).form("indefinite")
```

It does not generate `a` versus `an` from spelling.

Request a counted form:

```rust
txa(
    "Create {creature_count} {creature_noun}.",
    tx_args![
        creature_count,
        creature_noun => counted(
            subtype.term_id(),
            creature_count,
        ),
    ],
    "Creation rule with a runtime-selected counted noun.",
)
```

`counted(id, number)` is shorthand for:

```rust
term(id).form("counted").number(number)
```

The count selects the term surface. The separate placeholder renders the
number.

Keep fixed vocabulary inline:

```rust
txa(
    plural(card_count, [
        one("Draw {card_count} card."),
        other("Draw {card_count} cards."),
    ]),
    tx_args![card_count],
    "Rules text instructing the player to draw cards.",
)
```

Create a term only when a runtime-selected concept needs a form, count, locale
facet, or deliberately centralized proper name.

`opaque(value)` inserts an atomic localized value. The nested value must be one
text leaf with no arguments or selectors. If it needs grammatical interaction,
model it as a term.

### Application-annotated placeholders

Trox translations remain plain text. Translators cannot author HTML, Markdown,
component syntax, or other interpreted rich-text markup. Applications can,
however, attach opaque metadata to a message's existing named placeholders and
use that metadata at the final presentation boundary. This is structured
placeholder resolution, not rich-text parsing.

In Rust, annotate a still-lazy `LocalizedString` without a `Localizer`:

```rust
use trox::prelude::*;

#[derive(Debug)]
struct EntityAnnotation {
    entity_id: String,
}

let message = txa(
    "Gain {offered_card}.",
    tx_args![offered_card => opaque(card_name)],
    "An effect granting the displayed card.",
);
let annotated = message.annotate([(
    "offered_card",
    EntityAnnotation { entity_id: "card-7".into() },
)])?;

let parts = localizer.resolve_parts_checked(&annotated)?;
```

Rust's `annotate` consumes the cheap-to-clone `LocalizedString` and accepts any
`IntoIterator` of `(name, metadata)` pairs, including arrays, `Vec`, and owned
`BTreeMap` values. Duplicate names are rejected instead of being silently
overwritten.

`ResolvedLocalizedPart::Literal` contains translator-authored literal runs.
`ResolvedLocalizedPart::Placeholder` contains the semantic placeholder name,
its display-ready localized surface, and `Option<&EntityAnnotation>`.

The TypeScript lifecycle is equivalent:

```ts
const message = txa(
  "Gain {offered_card}.",
  { offered_card: opaque(cardName) },
  "An effect granting the displayed card.",
);
const annotated = message.annotate({
  offered_card: { kind: "entity", entityId: "card-7" },
});

const parts = localizer.resolvePartsChecked(annotated);
```

Construction, annotation, view-model storage, and application-layer transport
remain locale independent. Only `resolve_parts_checked` / `resolvePartsChecked`
and their recovering counterparts require the active `Localizer`. A target row
may reorder, repeat, or omit declared placeholders: the part sequence follows
that target row exactly, repeated occurrences reference the same annotation,
and omitted occurrences produce no part. Other placeholders resolve normally
with no annotation.

Placeholder `value` fields are display-ready and include FSI/PDI controls when
the bundle enables bidirectional isolation. Concatenating every part's `value`
is therefore exactly equal to `resolve_checked` / `resolveChecked` (and likewise
for recovering resolution). Scalar text, formatted numbers, terms, and opaque
nested localized values use the same formatting and recovery path as ordinary
string resolution.

Annotations are application data, not localization data. The Rust wrapper owns
its metadata and resolved parts borrow it; the TypeScript wrapper retains the
application values by reference in a shallow-frozen name map. Neither wrapper
implements Trox canonical serialization, and TypeScript `JSON.stringify`
rejects it explicitly. To cross a process or persistence boundary, serialize
the underlying `LocalizedString` through its existing canonical wire format and
serialize application metadata through an application-owned protocol, then
validate the names again by calling `.annotate(...)` on the decoded
`LocalizedString`. Unknown annotation names fail immediately with
`trox.unknown-annotation`.

### Resolution and rejected forms

```rust
let text = localizer.resolve(&value);
let checked = localizer.resolve_checked(&value)?;
let json = value.to_canonical_json()?;
let decoded = localizer.localized_string_from_json(&json)?;
```

Decoding validates IDs, schemas, selectors, numeric ranges, terms, and limits.
Patterns, branches, arguments, and descriptions must stay inline. Dynamic
patterns, concatenation, missing descriptions, numeric `select`, `concat!`, and
arbitrary localized nesting are rejected.

## TypeScript syntax

```ts
import {
  Localizer,
  counted,
  exact,
  few,
  indefinite,
  assertLocalized,
  one,
  opaque,
  ordinal,
  other,
  otherwise,
  plural,
  select,
  termId,
  two,
  tx,
  txa,
  when,
  type LocalizedString,
  type TermId,
} from "@trox/runtime";
```

Static and interpolated messages mirror Rust:

```ts
export function closeLabel(): LocalizedString {
  return tx(
    "Close deck browser",
    "Accessible label that closes the deck browser.",
  );
}

export function deckLabel(deck_name: string): LocalizedString {
  return txa(
    "Deck: {deck_name}",
    { deck_name },
    "Label followed by the user-defined deck name.",
  );
}
```

Use `assertLocalized(rawString)` for migrations, verbatim user input, tests, and
developer-only surfaces. It returns a `LocalizedString` that resolves to
`rawString` in every locale and is deliberately not extracted:

```ts
export function playerName(rawString: string): LocalizedString {
  return assertLocalized(rawString);
}
```

Calling it asserts that the text does not need translation at that call site;
do not use it for ordinary user-facing product copy. Replace migration uses
with `tx` or `txa` as localization work is completed.

The argument object must be inline. Spreads and prebuilt objects are not
extractable.

Cardinal and ordinal selection:

```ts
export function cardsRemaining(
  card_count: number,
): LocalizedString {
  return txa(
    plural(card_count, [
      exact(0, "No cards remain."),
      one("{card_count} card remains."),
      other("{card_count} cards remain."),
    ]),
    { card_count },
    "Status text showing cards remaining in the deck.",
  );
}

export function turnPosition(
  turn_number: number,
): LocalizedString {
  return txa(
    ordinal(turn_number, [
      one("{turn_number}st turn"),
      two("{turn_number}nd turn"),
      few("{turn_number}rd turn"),
      other("{turn_number}th turn"),
    ]),
    { turn_number },
    "Label for a turn's ordinal position.",
  );
}
```

Semantic selection uses finite literal unions:

```ts
type BattleZone = "deck" | "hand" | "void";

export function searchZone(zone: BattleZone): LocalizedString {
  return tx(
    select(zone, [
      when("deck", "Search your deck."),
      when("hand", "Search your hand."),
      when("void", "Search your void."),
      otherwise("Search that zone."),
    ]),
    "Rules text directing the player to search a zone.",
  );
}
```

Map application values to explicit `TermId` values, then use `indefinite`,
`counted`, or `opaque` exactly as in Rust. Resolve and serialize explicitly:

```ts
const text: string = localizer.resolve(value);
const json: string = value.toCanonicalJSON();
const decoded = localizer.localizedStringFromJSON(json);
```

`LocalizedString` is not assignable to `string`. Host interpolation, prebuilt
or spread argument objects, and dynamic descriptions are rejected. Single and
double quotes and template literals without interpolation are accepted. The
scanner handles `.ts` and `.tsx` without module resolution.

## RON source extraction

RON supports flat static messages and text templates with explicitly typed
placeholders:

```ron
(
    internal_id: "close-deck-browser",
    label: Tx("Close deck browser"),
    accessibility_label: Tx(
        text: "Close deck browser",
        description: "Accessible label that closes the browser.",
    ),
    open_state: Tx(
        text: "Open",
        meaning: "open-state",
        description: "Status for a room accepting players.",
    ),
    deck_summary: Tx(
        text: "Deck: {deck_name} ({count})",
        description: "Deck label followed by its card count.",
        placeholders: {
            "deck_name": Opaque,
            "count": Scalar,
        },
    ),
)
```

Rules:

- Only `Tx` records are extracted.
- Use the short `Tx("text")` form for plain static text.
- Use the named form when supplying `description` or `meaning`; `text` is
  required.
- `description`, `meaning`, and `placeholders` are optional named fields.
- Every placeholder in `text` must have exactly one declaration. Use `Scalar`
  for text, finite numbers, or booleans; `Opaque` for an atomic localized
  value; and `Term(form: "counted", number: true)` for a term with an exact
  form and number-presence contract.
- Generated descriptions include the structural RON field path, such as
  `Path: CardDefinition.ability_text`. Array indexes are omitted so every value
  in the same field shares a stable path.
- Unwrapped strings are ignored.
- Selectors are rejected. RON templates are text patterns only.
- Runtime argument values are not embedded in RON; only their schemas are
  declared.
- `{{` and `}}` render visible braces.

Rejected by source extraction:

```ron
(
    ignored: "Close deck browser",
    undeclared: Tx(text: "Deck: {deck_name}"),
    extra: Tx(text: "Deck", placeholders: { "deck_name": Opaque }),
)
```

Configure description defaults for authored data:

```ron
ron_description_defaults: {
    "data/cards.ron": "Rules text for a game card.",
    "data/**/*.ron": "Player-authored game data label.",
},
```

An explicit description overrides a matching path default. The structural RON
field path is appended to either description; when neither is present, the path
itself supplies the description.

### Serde round-tripping

Application-owned Rust types may contain `LocalizedString` fields and derive
Serde normally:

```rust
#[derive(Debug, PartialEq, serde::Serialize, serde::Deserialize)]
struct Record {
    label: LocalizedString,
}

let record = Record {
    label: tx("Foo", "Example label."),
};
let encoded = ron::to_string(&record)?;
assert_eq!(encoded, r#"(label:Tx("Foo"))"#);

let decoded: Record = ron::from_str(&encoded)?;
assert_eq!(decoded, record);
```

This application-data representation uses the same `Tx` forms as source
extraction. A value without a meaning serializes as `Tx("Foo")`; a value with
a meaning uses the named form `Tx(text: "Open", meaning: "open-state")` so the
meaning survives the round trip. Selectors and already-bound dynamic values
return a RON serialization error.

A placeholder-bearing `Tx` deserializes as an unbound template. Bind its
runtime values before canonical serialization or localization:

```rust
let template: LocalizedString = ron::from_str(
    r#"Tx(
        text: "Deck: {deck_name} ({count})",
        placeholders: { "deck_name": Opaque, "count": Scalar },
    )"#,
)?;
let value = template.bind_ron_template(tx_args![
    deck_name => opaque(tx("Night Garden", "Deck name.")),
    count => 40_u32,
])?;
let rendered = localizer.resolve_checked(&value)?;
```

### Transporting RON messages without text lowering

Use a `SourceMessageRef` when application data must cross a Rust-to-TypeScript
boundary before runtime arguments are available. The reference contains only
stable entry, identity, and contract signatures. It contains neither English
source text nor runtime argument values.

```rust
let template: LocalizedString = ron::from_str(
    r#"Tx(text: "Erode {count}", placeholders: { "count": Scalar })"#,
)?;
let source_ref = template.source_message_ref()?;
let json = source_ref.to_canonical_json()?;
```

Authorize the parsed reference with the deployed source bundle, then bind its
exact typed argument contract:

```ts
const message = sourceCatalog.sourceMessageFromJSON(json);
const localized = message.bind({ count: 3 });
const rendered = localizer.resolve(localized);
```

`sourceMessageFromValue` accepts an already-parsed JSON value. A
`SourceMessage` exposes an immutable `argumentSchemas` record and rejects
missing, extra, wrong-kind, unauthorized term-form, and non-atomic opaque
bindings. Static references bind with an empty record. Rust provides the same
catalog authorization and `SourceMessage::bind` contract.

The bound argument names and kinds must exactly match their declarations. Term
bindings must also match the declared form and whether a number is present.

Descriptions do not round-trip through `LocalizedString`. They are authoring
metadata and are not retained in the runtime value or message identity. For
example, `Tx(text: "Foo", description: "Example label.")` can be read, but
serializing the resulting value produces `Tx("Foo")`.

## Term catalog

`terms.ron` is one top-level map:

```ron
{
    "card-subtype.warrior": (
        description: "The Warrior card subtype.",
        value: "Warrior",
        forms: {
            "indefinite": "a Warrior",
            "counted": Number([
                One("Warrior"),
                Other("Warriors"),
            ]),
        },
    ),
}
```

Rules:

- A term has one stable ID and default value.
- Named forms are declared by project configuration.
- Numbered forms contain CLDR cardinal surfaces.
- Terms do not reference terms or messages.
- Source calls authorize exact form and number contracts.
- Fixed vocabulary stays in complete messages.

## Project configuration

Minimal complete `trox.ron`:

```ron
(
    source_locale: "en-US",
    terms: "terms.ron",
    source_bundle: ".trox-output/bundles/en-US.trox.json",
    source_report: ".trox-output/reports/en-US.csv",

    sources: [
        (
            language: Rust,
            include: ["src/**/*.rs"],
            exclude: [],
        ),
        (
            language: TypeScript,
            include: ["web/**/*.ts", "web/**/*.tsx"],
            exclude: [],
        ),
        (
            language: Ron,
            include: ["data/**/*.ron"],
            exclude: [],
        ),
    ],

    locales: {
        "es": (
            profile: "locales/es.ron",
            csv: ".trox-output/reports/es.csv",
            bundle: ".trox-output/bundles/es.trox.json",
        ),
    },

    max_expanded_rows_per_entry: 256,

    term_forms: {
        "counted": (
            description: "Term inflected for a cardinal count.",
            number: Required,
        ),
        "indefinite": (
            description: "Nonspecific singular noun phrase.",
            source_fallback: Default,
        ),
    },

    ron_description_defaults: {
        "data/**/*.ron": "Player-authored game data label.",
    },
)
```

The CLI discovers the nearest parent `trox.ron`. Select another complete
configuration with:

```sh
trox --config path/to/trox.ron check
```

## Locale profiles

Spanish example:

```ron
(
    locale: "es",
    direction: Ltr,
    isolation: Isolate,
    fallbacks: ["en-US"],

    facets: {
        "gender": (
            scope: Message,
            values: ["masculine", "feminine"],
        ),
    },

    term_facets: {
        "card-subtype.warrior": {
            "gender": "masculine",
        },
        "card-subtype.relic": {
            "gender": "feminine",
        },
    },
)
```

Profiles own:

- Locale identifier and fallback chain.
- Left-to-right or right-to-left direction.
- Placeholder isolation behavior.
- Locale-private facet IDs and values.
- Term classification under those facets.

Message-scoped facets expand containing messages into rows. Term-scoped facets
remain term context. Application code passes stable term IDs, not Spanish
gender or other locale-private metadata.

Trox does not guess grammar from spelling, person names, or machine
translation. Pass explicit semantic values when agreement requires them.

## Extraction and CSV

Commands:

```sh
# Validate without writes.
trox check
trox check --deny warnings
trox --json check

# Synchronize every locale or one locale.
trox extract
trox extract --locale ru

# Scaffold a locale.
trox locale init pl

# Build strict or development bundles.
trox bundle
trox bundle --locale es
trox bundle --allow-missing

# Extract, generate, and validate all production artifacts in one release job.
trox release-check
trox release-check --allow-missing

# Remove reviewed obsolete rows.
trox prune --locale es

# Create and merge a curated translator workbook.
trox handoff export --locale es --output localization/handoff/es.xlsx
trox handoff import --locale es --input localization/handoff/es.xlsx
```

Extraction is transactional:

- It validates every requested output before replacement.
- Any failure leaves all requested outputs unchanged.
- Successful replacements are atomic.
- Repeated extraction without changes is byte-identical.
- Parallel scanning does not change output order.
- Message rows follow source path, then numeric line and column. When the same
  message appears more than once, its earliest occurrence determines its
  position.

`trox check` always validates source code, terms, locale profiles, expansion,
and lint policy. When a configured CSV exists it validates that managed state
too; a missing generated CSV or JSON bundle is not an error. `trox extract`
creates catalogs from scratch, and `trox release-check` performs extraction
followed by production bundle generation and validation. Keep its configured
destinations in an ignored output directory and publish them from localization
or packaging automation instead of committing them.

Extraction preserves:

- Existing translations.
- Translator notes.
- Unknown workflow columns.
- Previous translations for changed rows.
- Removed rows as obsolete records in target-locale CSVs.

Row state:

- New untranslated rows are missing.
- Translator-relevant source changes make rows stale.
- Removed source or expansion rows become obsolete in target-locale CSVs.
- Obsolete rows are removed automatically from the English source report; target
  CSVs retain them until explicit pruning.

Representative translator-facing CSV columns (managed metadata follows):

```csv
english,description,translation
{count} card,"Card count label.\n\nConditions: count.plural=one",
{count} cards,"Card count label.\n\nConditions: count.plural=other",
```

Managed IDs are tool-owned. Selector conditions are included in the description
so translators can read all source context in one column; translators edit
surface text and notes, not selectors.

For an external translator, use `trox handoff export` instead of sending the
canonical CSV. The `.xlsx` handoff contains active rows only; obsolete rows and
unknown workflow columns remain in the canonical CSV as translation memory.
Only the Translation and Translator note columns are editable. Managed metadata
is hidden and protected, and every cell is written as spreadsheet text so source
strings beginning with `=`, `+`, `-`, or `@` cannot become formulas.

`trox handoff import` rejects formulas, added or removed rows and columns,
modified IDs, source metadata, or placeholder declarations, a changed source
catalog, and canonical CSV edits made after export. Imported translations also
run the project's normal placeholder and localization lint policy. A hidden
manifest binds the workbook to the locale, source locale, active row set, and
catalog fingerprint. Worksheet protection is for editing guidance; import
validation is the integrity boundary.

Condition examples:

```text
card_count.exact=0
card_count.plural=few
turn_number.ordinal=other
zone.select=deck
subtype.gender=feminine
```

An exact translation cell containing `^` inherits the resolved translation
from the immediately preceding active row of the same entry:

```csv
description,translation
"Conditions: subtype.gender=masculine",Crear {count} Guerrero.
"Conditions: subtype.gender=feminine",^
```

Caret rules:

- `^` cannot cross an entry boundary.
- Blank cells remain missing.
- Consecutive carets resolve through prior active rows.
- Bundles materialize inherited text.
- Extraction protects meaning when adjacency changes.

Rows become stale when text, description, selector context, argument schema,
term-form request, or locale expansion changes. The old translation is kept in
`previous_translation`.

Run extraction before pruning. `prune` rejects a CSV that no longer matches the
current catalog, so a row that became active again is not deleted.

### Lint policy

```ron
lint: (
    default_warning: Warn,
    rules: {
        "trox.unchanged-translation": (
            level: Deny,
        ),
        "trox.human-row-expansion": (
            level: Allow,
            reason: "Reviewed translator cost in issue 123.",
        ),
    },
),
```

Rules:

- `Warn` reports a warning.
- `Deny` promotes a warning to an error.
- `Allow` requires a nonempty review reason.
- Reasons on `Warn` or `Deny` are invalid.
- Expansion above 32 rows requires reasoned suppression.
- The configured row limit remains a hard cap.

One-run overrides:

```sh
trox --lint trox.unchanged-translation=deny check

trox --allow \
  'trox.human-row-expansion=Reviewed translator cost in issue 123.' \
  check
```

JSON diagnostics include a stable rule ID, severity, path, source span when
known, explanation, and suggested correction. `trox.internal` means an
implementation failure, not an ordinary authoring error.

## Bundles and runtime

Production bundle operations emit:

- The configured source bundle.
- Every selected target bundle.

Deploy one source bundle and one active target bundle:

```text
source bundle ─┐
               ├─> Localizer ─> resolve(LocalizedString) ─> String
target bundle ─┘
```

Applications retain ownership of filesystem, asset, or network I/O:

```rust
let source_json = load_asset("locales/en-US.trox.json")?;
let target_json = load_asset("locales/es.trox.json")?;
let source = trox::Bundle::from_canonical_json(&source_json)?;
let target = trox::Bundle::from_canonical_json(&target_json)?;
let localizer = trox::Localizer::new_strict(target, source)?;
# Ok::<(), Box<dyn std::error::Error>>(())
# fn load_asset(_: &str) -> Result<String, std::io::Error> { unreachable!() }
```

`Localizer::new` retains entry-level compatible fallback during a catalog
mismatch; `Localizer::new_strict` rejects the mismatch. Replace the explicit
`Localizer` value to change the active runtime locale. Trox performs no implicit
locale discovery and holds no global locale state.

Bundles are canonical JSON containing:

- Explicit format version.
- Pinned locale-data version.
- Source-catalog fingerprint.
- Canonical entry and row IDs.
- Target plural and ordinal behavior.
- Direction and isolation settings.
- Validated term forms and facet metadata.

The source bundle authorizes message identities, full signatures, visible
argument schemas, terms, and forms. Version 1.1 bundles also carry a contract
signature derived from the identity and argument schemas. Target bundles
contain translated rows and compatibility data.

Loading rejects unknown major versions, unsupported features, noncanonical
JSON, duplicate IDs, irreproducible IDs, invalid paths, and invalid signatures.

A catalog mismatch can preserve entry-level compatibility in normal mode.
Version 1.1 entries require matching contract signatures; version 1.0 entries
use their stable source signatures. Incompatible entries use source fallback.
Strict construction rejects any catalog-fingerprint mismatch.

Runtime responsibilities:

- Resolve selectors with target locale rules.
- Format numeric placeholders as locale decimals.
- Resolve terms and message-scoped facets.
- Apply configured directional isolation.
- Reorder, repeat, or omit declared placeholders.
- Emit diagnostics with visible source fallback.

Application responsibilities:

- Load bundle bytes.
- Choose the active target locale.
- Construct and distribute the `Localizer`.
- Keep `LocalizedString` unresolved in non-presentation layers.
- Use checked resolution for tests and validation.

The runtime does not read files, fetch resources, discover locale state, mutate
globals, parse CSV, run extraction, or evaluate translator-authored code.

## Identity and compatibility

Entry IDs hash canonical JSON containing the identity version, meaning key,
pattern structure, source leaves, and branch order. Descriptions, locations,
runtime values, dynamic term IDs, and host predicates do not define identity.

Descriptions and argument contracts still affect source revision or signature,
so their changes can stale translations without changing the entry ID.

Stable IDs are at most 96 ASCII bytes and match:

```text
[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*
```

Numeric branches use exact values in ascending order, followed by `zero`,
`one`, `two`, `few`, `many`, and `other`. Generic `select` keeps authored order
and puts `otherwise` last.

## Validation and conformance

`trox check` validates:

- Configuration and source globs.
- Rust, TypeScript, TSX, and RON syntax.
- Terms and named forms.
- Locale profiles and term classifications.
- Existing managed CSV state when present; generated artifacts are optional.
- Placeholders and selector branches.
- Target row expansion.
- Lint policy and reasons.

Runtime loading validates:

- Bundle and wire versions.
- Canonical encoding.
- Catalog fingerprints.
- Entry signatures and argument schemas.
- Selector values and paths.
- Term authorization.
- Expansion row IDs.

Shared fixtures cover static and dynamic identities, canonical wire bytes,
source-message references, argument authorization, nested selectors, lookup,
legacy version upgrades, and fallback.

Before changing identity, bundle, or wire behavior, run:

```sh
cargo test --workspace
npm run typecheck
npm test

trox --config crates/trox-cli/tests/fixtures/quest/trox.ron extract
trox --config crates/trox-cli/tests/fixtures/quest/trox.ron check
trox --config crates/trox-cli/tests/fixtures/quest/trox.ron bundle --allow-missing
```

Confirm that a second extraction is byte-identical. The benchmark uses 100 MiB
of equal Rust, TypeScript, TSX, and RON source with 10,000 calls:

```sh
trox benchmark \
  --synthetic-mib 100 \
  --iterations 5
```

Gates are warm startup below 50 ms, throughput of at least 200 MiB/s, peak RSS
below twice the source size, and an optional 15 percent median regression cap.

## Terminology

- **Argument**: runtime value bound to a visible placeholder.
- **Atomic localized value**: text leaf with no arguments or selectors,
  inserted explicitly through `opaque`.
- **Bundle**: deterministic runtime JSON for source or target locale data.
- **Cardinal**: quantity category selected by `plural`.
- **Caret inheritance**: CSV `^` shorthand for the preceding active row.
- **Catalog fingerprint**: digest pairing compatible source and target bundles.
- **Condition**: read-only CSV label for one selector or facet choice.
- **Description**: translator context attached to a message or term.
- **Entry**: one extracted message family or term-form family.
- **Entry ID**: content-derived versioned message identifier.
- **Exact branch**: numeric branch checked before a CLDR category.
- **Facet**: locale-owned term metadata such as grammatical gender.
- **Fallback**: visible source text used when target data is unusable.
- **Form**: declared semantic term surface such as `indefinite`.
- **Identity descriptor**: canonical structure hashed into an entry ID.
- **Locale profile**: direction, isolation, fallback, and facet configuration.
- **LocalizedString**: immutable unresolved message value.
- **Localizer**: resolver built from one source and one target bundle.
- **Meaning key**: discriminator for identical text with different semantics.
- **NFC**: required Unicode Normalization Form C.
- **Opaque**: assertion that a localized value is grammatically atomic.
- **Ordinal**: position category selected by `ordinal`.
- **Pattern**: text leaf or finite selector tree of complete leaves.
- **Placeholder**: named insertion point such as `{card_name}`.
- **RON**: Rusty Object Notation used for checked static data.
- **Row**: one translation unit after locale-specific expansion.
- **Scalar**: visible text, finite number, or boolean argument.
- **Select**: finite semantic branch using a stable application value.
- **Selector**: plural, ordinal, or semantic pattern node.
- **Source catalog**: runtime authority for identities and argument contracts.
- **Source report**: source-locale CSV describing extracted rows.
- **Source revision**: translator context that may stale a row.
- **Source signature**: digest proving exact source compatibility.
- **Stale row**: active row whose source context changed.
- **Term**: stable lexical concept used for runtime grammar.
- **Translation row**: flat CSV record containing one editable pattern.
- **Wire value**: canonical serialized `LocalizedString`.