stkcraft-time 0.2.0

NAIF/SPICE-aligned astronomical time scales in Rust: UTC, TAI, TT, TDB/ET, GPS, UT1 and SCLK, with LSK/SCLK/EOP kernels, no_std support, WebGeocalc parity and an MCP server.
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
<p align="center">
  <img src="https://raw.githubusercontent.com/spacelibres/STKCraft_web/main/public/brand/albatross.png" alt="STKCraft — Albatross" width="72">
</p>

<p align="center">
  <a href="https://crates.io/crates/stkcraft-time">crates.io</a> ·
  <a href="https://docs.rs/stkcraft-time">API reference</a> ·
  <a href="https://github.com/spacelibres/STKCraft-time">source</a> ·
  <a href="https://github.com/spacelibres/STKCraft-time/wiki">wiki</a> ·
  <a href="https://www.stkcraft.com">STKCraft</a>
</p>

# `stkcraft-time` API guide

This guide shows how to call the public API of `stkcraft-time` 0.2.0. It
is task-oriented: each section answers "which function do I call, and what
data do I need to load first?" For item-level reference documentation,
run:

```sh
cargo doc --open
```

A runnable version of the main examples is
[`examples/api_tour.rs`](../examples/api_tour.rs):

```sh
cargo run --example api_tour
```

Code snippets assume a function returning `Result<_, TimeError>` and that
values introduced in earlier snippets (`lsk`, `eop`, `utc`, ...) are in
scope unless the snippet redefines them.

Three sources describe this crate, and they have distinct jobs:

| Source | Role |
|---|---|
| This file | Authoritative in-repository API contract and call patterns |
| [`TIME_CONTRACT.md`]TIME_CONTRACT.md | Model contracts: units, origins, model bounds, reproducibility |
| [Project wiki]https://github.com/spacelibres/STKCraft-time/wiki | Narrative explanations and the verification record |

If they ever disagree, this file and the source are correct; the wiki is
the narrative view and is updated from the same facts.

## 1. Scope and features

`stkcraft-time` is a `no_std`-capable library. It never performs network
I/O and does not bundle mission data. The caller supplies the mission data
files (spacecraft clock, EOP) at run time; a `naif0012.tls` snapshot is
compiled in as the default leap-second table, and an explicit LSK
replaces it.

| Cargo feature | Default | Effect |
|---|---|---|
| `std` | yes | Enables `impl std::error::Error for TimeError` and the CLI binaries. |
| `mcp` | no | Builds the `stkcraft-mcp` stdio MCP server; implies `std` and `serde_json`. |
| *(none)* | — | `no_std` + `alloc`; the library remains available, binaries are skipped. |

```toml
[dependencies]
stkcraft-time = "0.2.0"

# no_std + alloc:
# stkcraft-time = { version = "0.2.0", default-features = false }

# or pin the repository:
# stkcraft-time = { git = "https://github.com/spacelibres/STKCraft-time", tag = "v0.2.0" }
```

The internal epoch representation is integer seconds plus nanoseconds;
no floating-point accumulation is used for epoch or duration arithmetic.

## 2. What a SPICE kernel is

In the JPL WebGeocalc Time Conversion UI, **Kernel selection** chooses the
SPICE data files for the session. A SPICE *kernel* is a data file, not an
operating-system kernel. Only a subset participates in time conversion:

| WebGeocalc item | Kernel type | Purpose | `stkcraft-time` API |
|---|---|---|---|
| Latest leap-seconds kernel | LSK (`KPL/LSK`) | UTC–TAI leap seconds, `DELTET` constants | `LeapSecondTable::builtin` / `LeapSecondTable::from_lsk` |
| Spacecraft clock | SCLK (`KPL/SCLK`) | Mission clock ticks/strings ↔ ET/TAI | `SclkKernel::parse` |
| IERS EOP (not shown on that screen) | `finals2000A.all` | `UT1 - UTC` | `EopTable::from_finals2000a*` |
| Solar-system kernels | SPK/PCK | Trajectories and planetary constants | Not used for time conversion |
| Ground-station kernel set | Station kernels | Station locations | Not used for time conversion |
| `SPK/MK` | MK (meta-kernel) | A manifest listing other kernels | Not loaded; it is only a file list |

So the statement "each time system has its own kernel" is not quite right:
UTC/TT/TDB/GPS share the **LSK**, and only the spacecraft-clock encoding
needs a mission-specific **SCLK**. SPK/PCK/FK/IK contain geometry and
trajectory data; a pure time conversion neither loads nor needs them.
UT1 is the exception among time scales: it needs an independent **EOP**
table because it measures the actual rotation of the Earth.

### 2.1 Kernel date literals

A text kernel can give an epoch as a literal that begins with `@`, for
example `EPOCH = @2000-JAN-01-12:00:00`. NAIF resolves that literal with
`TPARSE` into **seconds past J2000**. It is a bare kernel constant, not a
UTC, TT or TDB value: no time-scale conversion takes place and no
leap-second kernel is consulted, so a date before 1972 is valid here even
when the UTC contract rejects it.

`stkcraft_time::kernel_date::parse_kernel_date` performs the same
resolution and also reports the normalized calendar fields:

```rust
use stkcraft_time::kernel_date::parse_kernel_date;

let epoch = parse_kernel_date("@2001-FEB-29")?;
assert_eq!(epoch.seconds_past_j2000, 36_676_800.0);
assert_eq!((epoch.year, epoch.month, epoch.day), (2001, 3, 1));
# Ok::<(), stkcraft_time::TimeError>(())
```

| Literal form | Example |
|---|---|
| `Y-MON-D` / `Y-MM-D` | `@2000-JAN-01` |
| `D-MON-Y` when the year token is four digits | `@31-JAN-1987` |
| `MON-D-Y` with `-` or `/` | `@March-7-1987`, `@feb/4/1987` |
| Any of the above with `HH[:MM[:SS]]` | `@2000-JAN-01-12:00:00` |

A month name is any prefix of at least three letters (`JAN`, `JANU`,
`JANUARY`), in any case. A decimal is accepted only in the final numeric
component of the literal, meaning the day or the clock's last field. A day
past the end of its month rolls forward exactly as NAIF does
(`@2001-FEB-29` is `2001-03-01`).

Year selection follows N0067 `TPARTV` token precedence, not an assumed
`DD-MON-YY` reading. An integer token of at least 1000 is a year; a year
token in `0..=99` expands over the native 1969--2068 window. `@31-JAN-1987`
is 1987-01-31, but `@19-JAN-87` is 2019-03-28: token `19` is the year and
token `87` is an out-of-range day that rolls forward. Mixed dash/slash
separators, `JD`-marked Julian dates and the exercised ISO ordinal forms
are supported. Standalone `@2000-060`, empty literals and unsupported
grammar return `TimeError::KernelDateUnsupported`; see the
[exact grammar scope](reference/KERNEL_DATE_GRAMMAR.md), which records the
416-input native corpus. Complete TPARSE grammar conformance is not
claimed. The error is deliberately separate from `LskMissing`/`SclkMissing`:
a present but unsupported literal must never be reported as an absent
kernel variable.

## 3. Quick start

```rust
use stkcraft_time::convert::{et_to_utc, utc_to_et};
use stkcraft_time::{Calendar, LeapSecondTable, UtcDateTime};

fn main() -> Result<(), stkcraft_time::TimeError> {
    // Bundled snapshot of naif0012.tls; use from_lsk in production.
    let lsk = LeapSecondTable::builtin()?;

    let utc = UtcDateTime::new(2000, 1, 1, 12, 0, 0.0);
    let et = utc_to_et(&utc, Calendar::Gregorian, &lsk)?;
    let back = et_to_utc(et, Calendar::Gregorian, &lsk)?;

    assert_eq!(stkcraft_time::format::iso8601(&back, 3), "2000-01-01T12:00:00.000Z");
    Ok(())
}
```

## 4. Loading and selecting a leap-second kernel (LSK)

### 4.1 Bundled snapshot vs explicit kernel

```rust
use stkcraft_time::{LeapSecondTable, TimeError};

fn load_lsk(path: &str) -> Result<LeapSecondTable, TimeError> {
    let text = std::fs::read_to_string(path).map_err(|_| TimeError::LskParse)?;
    LeapSecondTable::from_lsk(&text)
}
```

- `LeapSecondTable::builtin()` parses the bundled `src/naif0012.tls`.
  Its last entry is `2017-01-01`, so it is a convenience snapshot, not a
  privileged source of truth.
- `LeapSecondTable::from_lsk(text)` parses the `DELTET/*` variables of any
  complete `KPL/LSK` kernel. This is the production entry point. Missing
  `DELTA_T_A`, `K`, `EB`, `M` or `DELTA_AT` returns `LskMissing`; no nominal
  constant is silently substituted for the caller's data.
- `stkcraft_time::lsk::parse_lsk(text)` is the module-level function behind
  `from_lsk`; both are public.

### 4.2 Coverage and kernel selection

```rust
use stkcraft_time::calendar::gregorian_to_jdn;
use stkcraft_time::LeapSecondTable;

let lsk = LeapSecondTable::builtin()?;

let (first_jdn, last_jdn) = lsk.coverage();
println!("kernel covers JDN {first_jdn}..={last_jdn}");

let jdn = gregorian_to_jdn(2017, 1, 1);
assert_eq!(lsk.delta_at_for_jdn(jdn), Some(37));
```

Every conversion is a pure function of the supplied kernel. Two kernels
that disagree about a leap second give different results after the first
disagreement, exactly as selecting a different kernel in WebGeocalc does.
UTC dates before the first active entry return `TimeError::UtcOutOfRange`;
dates after the last entry keep the last `TAI - UTC` value.

### 4.3 Policies and the pre-1972 source

```rust
use stkcraft_time::calendar::gregorian_to_jdn;
use stkcraft_time::{
    LeapSecondPolicy, LeapSecondSource, LeapSecondTable,
};

let text = std::fs::read_to_string("naif0012.tls")?;
let lsk = LeapSecondTable::from_lsk(&text)?
    .with_source(LeapSecondSource::Sofa)
    .with_policy(LeapSecondPolicy::FrozenAfter {
        jdn: gregorian_to_jdn(2035, 1, 1),
    });
```

- `LeapSecondSource::IersOnly` (default) matches the NAIF LSK and handles
  integer leap seconds from 1972 onward for civil conversions. Earlier
  civil UTC is rejected; explicit native formal JDUTC is described below.
- `LeapSecondSource::Sofa` adds the IAU SOFA `iauDat` drift model for
  1960–1972 and returns fractional `TAI - UTC`.
- `LeapSecondPolicy::TableDriven` (default) keeps the last table entry in
  force forever.
- `LeapSecondPolicy::FrozenAfter { jdn }` ignores entries after the chosen
  date. `LeapSecondPolicy::frozen_after(year, month, day)` is a
  convenience constructor. This is an explicit caller assumption; the
  default path never infers a future policy from a date.

### 4.4 Building a table from entries

```rust
use stkcraft_time::calendar::gregorian_to_jdn;
use stkcraft_time::{LeapEntry, LeapSecondTable};

let lsk = LeapSecondTable::new(vec![
    LeapEntry { jdn: gregorian_to_jdn(1972, 1, 1), delta_at: 10 },
    LeapEntry { jdn: gregorian_to_jdn(2017, 1, 1), delta_at: 37 },
])?;
```

`LeapSecondTable::new` sorts entries by JDN, rejects duplicate effective
dates, and rejects a table whose TAI start instants are not strictly
increasing. `with_constants(delta_t_a, k, eb, m0, m1)` replaces the
`DELTET` constants when they come from an external source.

## 5. UTC and leap seconds

```rust
use stkcraft_time::convert::{tai_to_utc, utc_to_tai};
use stkcraft_time::{Calendar, LeapSecondTable, UtcDateTime};

let lsk = LeapSecondTable::builtin()?;

// Positive leap second: legal only at the end of a 86401-second day.
let leap = UtcDateTime::new(2016, 12, 31, 23, 59, 60.5);
let tai = utc_to_tai(&leap, Calendar::Gregorian, &lsk)?;
let back = tai_to_utc(tai, Calendar::Gregorian, &lsk)?;
assert!((back.second - 60.5).abs() < 1e-9);
```

Boundary behaviour:

| Input | Result |
|---|---|
| `23:59:60.x` on a positive-leap-second day | Accepted; the day has 86401 seconds. |
| `23:59:60.x` on any other day | `TimeError::InvalidLeapSecond` |
| `23:59:59.x` on a shortened (86399-second) day | `TimeError::InvalidLeapSecond` |
| `second` outside `0.0..61.0` | `TimeError::InvalidSecond` |
| Invalid month/day | `TimeError::InvalidDate` |
| `hour > 23` or `minute > 59` | `TimeError::InvalidTime` |
| UTC before the first active LSK entry | `TimeError::UtcOutOfRange` |

A negative leap second removes `23:59:59` from the preceding day. The
conversion rejects that label rather than aliasing it with the following
day's `00:00:00`.

## 6. Time-scale conversions

| From → To | Function | Requires |
|---|---|---|
| UTC → TAI | `convert::utc_to_tai` | LSK |
| TAI → UTC | `convert::tai_to_utc` | LSK |
| UTC → ET | `convert::utc_to_et` | LSK |
| ET → UTC | `convert::et_to_utc` | LSK |
| TAI → TT | `convert::tai_to_tt` | LSK |
| TT → TAI | `convert::tt_to_tai` | LSK |
| TAI → ET | `convert::tai_to_et` | LSK |
| ET → TAI | `convert::et_to_tai` | LSK |
| TAI → GPS | `convert::tai_to_gps` | — |
| GPS → TAI | `convert::gps_to_tai` | — |
| TAI → UT1 | `convert::tai_to_ut1` | LSK + EOP |
| UT1 → TAI | `convert::ut1_to_tai` | LSK + EOP |
| UTC → UT1 | `convert::utc_to_ut1` | LSK + EOP |
| UT1 → UTC | `convert::ut1_to_utc` | LSK + EOP |
| TAI → TCG | `coord::tai_to_tcg` | LSK |
| TCG → TAI | `coord::tcg_to_tai` | LSK |
| TAI → TCB | `coord::tai_to_tcb` | LSK |
| TCB → TAI | `coord::tcb_to_tai` | LSK |
| TAI → ESA TDB | `tdb::tai_to_tdb` | LSK |
| TAI → IAU TDB | `dtdb::tai_to_tdb_iau` | LSK |

The common core:

```rust
use stkcraft_time::convert::{
    et_to_tai, gps_to_tai, tai_to_et, tai_to_gps, tai_to_tt, tt_to_tai,
    utc_to_tai,
};
use stkcraft_time::{Calendar, LeapSecondTable, UtcDateTime};

let lsk = LeapSecondTable::builtin()?;
let utc = UtcDateTime::new(2016, 12, 31, 12, 0, 0.0);
let tai = utc_to_tai(&utc, Calendar::Gregorian, &lsk)?;

let tt = tai_to_tt(tai, &lsk);          // TAI + 32.184 s
let et = tai_to_et(tai, &lsk);          // NAIF ET, TDB s past J2000
let gps = tai_to_gps(tai);              // GPS s past 1980-01-06

let tai_again = tt_to_tai(tt, &lsk);
let tai_from_et = et_to_tai(et, &lsk);
let tai_from_gps = gps_to_tai(gps);
```

`GPS` is a continuous scale defined as `TAI - 19 s`; GPS↔TAI itself needs
no leap-second table. Conversions that involve UTC still need the LSK.

### WebGeocalc GPS week/TOW display

`wgc_gps::gps_seconds_to_week_tow(seconds, &lsk)` converts a binary64
GPS-epoch second input to the exercised WebGeocalc six-decimal week/TOW
string. The tested non-finite inputs produce WGC's literal `0, NaN`;
this is a display string and does not represent a valid numeric epoch. It performs the observed NAIF TAI→TDB→TAI round-trip using the
selected LSK before formatting. The displayed week saturates the integer
seconds to i32 before division, while the remainder uses the full value.
Shortest-decimal half-away rounding preserves negative zero and does not
carry a displayed 604800-second remainder into the week.

This compatibility path differs from exact integer-time arithmetic. It is
verified only for the documented live WGC2 and native samples; arbitrary
kernels, platforms, input strings and other WGC output formats remain open.
See `tests/reference/wgc-gps/README.md` for captured inputs and provenance.

`parse_week_tow` parses the observed WGC input syntax and reproduces the
signed 32-bit week multiplication before adding the binary64 time of week.
`week_tow_to_et` and `gps_seconds_to_et` return checked NAIF ET for finite
values. `et_to_gps_display_seconds` returns the WGC six-decimal numeric
display cell as binary64; it is not a lossless epoch. WGC accepts certain
non-finite GPS inputs and displays `NaN`; checked ET constructors reject
them rather than inventing an epoch.

`et_to_calendar_doy` and `et_to_calendar_ymd` take a `WgcCalendarSystem`
(`Utc`, `Tdb`, `Tt`, `Tdt`, or `Gps`) and return six-decimal WGC-style
strings. UTC requires the IERS-only, table-driven native LSK model. Its
pre-1972 behavior is the native TTRANS convention, not physical historical
UTC. The implementation follows the observed N0067 TIMOUT rounding path,
including its intermediate binary64 arithmetic and calendar reconstruction.
See `tests/reference/wgc-gps-input/README.md` for exact sample coverage.

These helpers do not implement the WGC request dispatcher, arbitrary CUSTOM
`timout` pictures, or the complete format/time-system combination matrix.
Some combinations documented as inapplicable are accepted or fall back in
the live service; see `format-combinations.json` rather than assuming a
validation error. The live server's kernel-set bytes were not independently
retrieved. No exhaustive WGC parity is claimed.

| WebGeocalc time format | Scope of these explicit helpers |
| --- | --- |
| `WEEK_TOW` | Tested input parsing and GPS display output; no generic request dispatch. |
| `SECONDS_PAST_GPS0` | Finite GPS numeric input to ET and six-decimal GPS numeric output. |
| `CALENDAR`, `CALENDAR_YMD`, `CALENDAR_DOY` | Tested YMD/DOY output; no complete WGC calendar-string input grammar. |
| `JULIAN` | No complete WGC-shaped input/output contract; the separate native JDUTC API has a narrower contract. |
| `SECONDS_PAST_J2000` | No WGC-shaped output-format/rounding contract in these helpers. |
| `SPACECRAFT_CLOCK_STRING`, `SPACECRAFT_CLOCK_TICKS` | Separate type-1 native SCLK APIs and documented limits. |
| `CUSTOM` | Arbitrary SPICE picture parsing/rendering is not provided. |

The WGC server's observed handling of some inapplicable combinations differs
from the published applicability table. See the captured requests rather
than applying a guessed rejection policy.

### 6.1 Which TDB model should I use?

For a checked integration surface, use `contract::TimeContext::new(&lsk)`
and its typed `NaifEt` result. This selects NAIF ET by construction.
`contract::ScientificContext` explicitly selects TT(TAI) and scientific
TDB, returning a separate `IauTdb` type. There is no implicit conversion
between those types. The scientific context ignores mutable LSK constants
and guards the model's 1950-2050 date interval. See
[Time contracts](TIME_CONTRACT.md) for units, origins, metadata and limits.

For native SPK10 initialization or another explicitly selected TTRANS
JDUTC consumer, use the direct checked scalar path. With the original
unmodified `naif0012.tls` already loaded as IERS-only/TableDriven `lsk`,
inside a function returning `Result<_, stkcraft_time::contract::ContractError>`:

```rust
use stkcraft_time::contract::{NaifEt, TimeContext};
let et = NaifEt::from_seconds(-1_000_000_000.0)?;
let utc_jd = TimeContext::new(&lsk).et_to_spice_julian_utc(et)?;
assert_eq!(utc_jd.days().to_bits(), 0x41429d9176751ee9);
```

The native historical convention and formal leap-second behavior are
distinct from physical historical UTC. SOFA/frozen policies are rejected
by this method; `et_to_utc` keeps its existing civil coverage. It preserves
native operation order and the first 140 leap entries without passing
through integer Epoch or civil calendar fields. See
[native JDUTC evidence and limits](reference/NATIVE_JDUTC.md).

#### Raw native leap-table errors

Use the separate `NaifUtcContext` when an original-order structured native
table must reach calculation even though the scientific constructor rejects
it. Supply every DELTET constant from the selected kernel. Inside a function
returning `Result<_, stkcraft_time::contract::ContractError>`:

```rust
use stkcraft_time::{LeapEntry, contract::{NaifDeltet, NaifEt, NaifUtcContext}};
let entries = [
    LeapEntry { jdn: 2441318, delta_at: 100000 },
    LeapEntry { jdn: 2441319, delta_at: 0 },
];
let deltet = NaifDeltet {
    delta_t_a: 32.184, k: 0.001657, eb: 0.01671,
    m0: 6.239996, m1: 1.99096871e-7,
};
let context = NaifUtcContext::from_raw_parts(&entries, deltet)?;
let error = context.et_to_spice_julian_utc(NaifEt::from_seconds(0.)?).unwrap_err();
assert_eq!(error.to_string(), "SPICE(BADLEAPSECONDS)");
```

Construction requires a nonempty slice and finite constants, preserves entry
order, and defers native paired-TAI validation until conversion. Only the first
140 entries participate, including validation. `LeapSecondTable::new` retains
its sorting and `LskParse` contract; do not use it to normalize this raw input.
This explicit Rust API covers integral Julian dates and whole-second offsets.
It is not an arbitrary kernel-pool parser or a new MCP schema. Successful
results remain checked `NaifJulianUtc` values rather than implicit ET/Epoch.

| API | Model | Use when |
|---|---|---|
| `convert::tai_to_et` / `et_to_tai` | NAIF one-term `K*sin(E)` | You need NAIF/SPICE/CSPICE compatibility. |
| `tdb::tai_to_tdb` / `tdb_to_tai` | NASA HEASARC compact two-term | You need this approximate relation; not a guaranteed improvement over NAIF. |
| `dtdb::tai_to_tdb_iau` / `tdb_iau_to_tai` | IAU Fairhead–Bretagnon 787-term | You need IAU/SOFA `dtdb` compatibility. |

The models are not interchangeable. `ET` is an `f64` by definition.
The compact model follows [NASA HEASARC](https://heasarc.gsfc.nasa.gov/docs/xte/abc/time_tutorial.html);
its maximum residual against geocentric ERFA on a daily 1950-2050 grid
is about 36.5 us. The existing `dtdb::tai_to_tdb_iau` model is geocentric.
`dtdb_minus_tt_at_observer` and `ScientificContext::to_tdb_at_observer`
add explicitly supplied observer-dependent SOFA/ERFA terms. They require
UT1 fraction, east-positive longitude in radians and cylindrical observer
distances in km. Spacecraft proper-time transformations are not
implemented. Nanosecond model accuracy does not imply nanosecond
resolution for an absolute `f64` seconds value.

## 7. UT1 and IERS Earth Orientation Parameters

UT1 cannot be derived from the LSK. It needs an IERS `finals2000A.all`
table that measures `UT1 - UTC`. This API interpolates daily EOP values.
It omits the subdaily ocean-tide and libration terms required by
[IERS Conventions section 5.5.3.1](https://iers-conventions.obspm.fr/content/chapter5/icc5.pdf)
for high-accuracy instantaneous Earth orientation, and does not propagate
measurement/prediction uncertainties. `observed_only()` filters predictions,
not measurement error.

### 7.1 Parsing an EOP file

```rust
use stkcraft_time::eop::{EopSeries, EopTable};

let text = std::fs::read_to_string("finals2000A.all")
    .map_err(|_| stkcraft_time::TimeError::EopParse)?;

// Bulletin A (the default).
let eop = EopTable::from_finals2000a(&text)?;

// Bulletin B where present, otherwise Bulletin A, matching astropy's
// combined column.
let eop = EopTable::from_finals2000a_series(&text, EopSeries::FinalPreferred)?;

// Restrict the supported interval to measured values.
let observed = eop.observed_only()?;
let (first_mjd, last_mjd) = observed.range();
```

`EopTable::new(samples)` is available when you already have samples:

```rust
use stkcraft_time::eop::{EopSample, EopTable};

let eop = EopTable::new(vec![
    EopSample { mjd: 57_753.0, ut1_minus_utc: -0.4089, observed: true },
    EopSample { mjd: 57_754.0, ut1_minus_utc: 0.5911, observed: true },
    EopSample { mjd: 57_755.0, ut1_minus_utc: 0.5907, observed: true },
])?;
```

`new` requires a non-empty table and rejects non-finite `mjd` or
`ut1_minus_utc` values with `TimeError::EopParse`.

### 7.2 Raw interpolation vs leap-aware UT1

```rust
use stkcraft_time::convert::{tai_to_ut1, ut1_minus_utc, utc_to_tai, utc_to_ut1};
use stkcraft_time::{Calendar, LeapSecondTable, UtcDateTime};

// `eop` is the EopTable loaded in section 7.1.
let lsk = LeapSecondTable::builtin()?;
let utc = UtcDateTime::new(2016, 12, 31, 23, 59, 60.5);
let tai = utc_to_tai(&utc, Calendar::Gregorian, &lsk)?;

// Raw table interpolation. It does not remove the leap-second step.
let raw = eop.ut1_minus_utc(57_753.5)?;

// Leap-aware: each EOP sample is converted to continuous UT1-TAI
// before interpolation, so a missing day across a leap second does not
// smear the step.
let offset = ut1_minus_utc(tai, &lsk, &eop)?;

// Continuous UT1 seconds past 2000-01-01T00:00:00 UT1.
let ut1 = tai_to_ut1(tai, &lsk, &eop)?;
let ut1_from_utc = utc_to_ut1(&utc, Calendar::Gregorian, &lsk, &eop)?;
```

Use `convert::ut1_minus_utc` for epochs on the UT1 scale.
Use `EopTable::ut1_minus_utc` only for table inspection or when the
leap-second step is irrelevant.

The leap-aware conversion interpolates `UT1 - TAI`, not raw `UT1 - UTC`.
The EOP table must contain a sample on or before the epoch's UTC day and a
later sample; the last sample day is not usable as an epoch boundary.
Missing days inside the table are handled as a continuous gap, without
reintroducing a leap-second step.

## 8. Spacecraft clock kernels (SCLK)

Only type-1 clocks are supported. No SCLK is embedded at runtime; load the mission
kernel you need.

```rust
use stkcraft_time::sclk::{SclkKernel, SclkTimeSystem};
use stkcraft_time::LeapSecondTable;

let lsk = LeapSecondTable::builtin()?;

const SYNTH_SCLK: &str = r#"
KPL/SCLK

\begindata

SCLK_DATA_TYPE_999       = ( 1 )
SCLK01_TIME_SYSTEM_999   = ( 1 )
SCLK01_N_FIELDS_999      = ( 2 )
SCLK01_MODULI_999        = ( 1000 100 )
SCLK01_OFFSETS_999       = ( 0 0 )
SCLK01_OUTPUT_DELIM_999  = ( 2 )
SCLK01_COEFFICIENTS_999  = (
    0.0000000000000E+00     0.0000000000000E+00     1.0000000000000E+00
    1.0000000000000E+05     1.0000000000000E+03     1.0000000000000E+00
)

\begintext
"#;

let sclk = SclkKernel::parse(SYNTH_SCLK, -999)?;
assert_eq!(sclk.time_system(), SclkTimeSystem::Tdb);
assert_eq!(sclk.n_fields(), 2);

let fields = sclk.parse_string("123:45")?;            // [123, 45]
let ticks = sclk.ticks_from_fields(&fields)?;         // 12345.0
let same_fields = sclk.fields_from_ticks(ticks)?;     // [123, 45]
let clock_string = sclk.format_string(&same_fields)?; // "123:45"

let et = sclk.ticks_to_et(ticks, &lsk)?;
let ticks_again = sclk.et_to_ticks(et, &lsk)?;

let tai = sclk.ticks_to_tai(ticks, &lsk)?;
let ticks_from_tai = sclk.tai_to_ticks(tai, &lsk)?;
```

- Numeric scalar assignments may omit parentheses; single-element moduli,
  offsets and partition bounds also support this NAIF syntax.
- `spacecraft_id` may be positive or negative; kernel variables are looked
  up with the magnitude (`-41` and `41` both find the `_41` variables).
- `SCLK01_OFFSETS` gives the first displayed value of each field. The
  encoded counter is `field - offset`; decoding adds the offset back. For
  a Voyager-like third field with offset 1, the displayed field
  `[0, 0, 1]` is encoded tick 0, not tick 2.
- `SclkTimeSystem::Tdb` coefficients are ET seconds past J2000 directly.
  `SclkTimeSystem::Tdt` coefficients are TT seconds past J2000 and use the
  LSK for the direct N0067 UNITIM TT↔ET step. Neither f64-to-f64
  direction detours through an integer Epoch; explicit TAI APIs retain
  their documented nanosecond quantization.
- `parallel_seconds(ticks)` and `ticks_from_parallel(seconds)` stop at the
  parallel time system; `ticks_to_et`/`et_to_ticks` and
  `ticks_to_tai`/`tai_to_ticks` perform the scale conversion. Continuous
  (non-integral) ticks are valid for all of these conversions.
- `fields_from_ticks` and `ticks_from_fields` operate on discrete encoded
  ticks. `fields_from_ticks` rejects a value more than 1e-6 from an
  integer; callers that only need ET/TAI should use the tick conversion
  functions directly.
- Partition boundaries are exposed through `partitions()`. The legacy
  `parse_string`, `format_string` and field-vector methods still reject
  multiple partitions or a nonzero start. Use `encode_native_sclk` and
  `decode_native_sclk` for partition-aware strings. To reproduce native
  parser history across calls, retain an explicit `SclkStringContext` and
  call `encode_native_sclk_with_context`; a fresh context resets that history.
  `SclkClock::native_sclk_to_et`, `native_sclk_to_et_with_context`, and
  `native_et_to_sclk` retain string errors in `NativeSclkError::String`,
  verified range errors in `NativeSclkError::Native`, and other time
  conversion errors in `NativeSclkError::Time`. The older
  `SclkMap` methods retain their existing `TimeError` interface.
  A finite clock string can produce a non-finite native ET for extreme
  coefficients, as observed in CSPICE; the raw Rust native ET method retains
  that result. Checked Python and JavaScript `NaifEt` wrappers reject it.
  Conversion to the bounded TAI `Epoch` returns `TimeError::Overflow` when
  the result is non-finite or outside its representable range.
  Non-finite native decode inputs return the library guard
  `STKCRAFT(NONFINITE)`, not a claimed CSPICE short error. On the tested
  Windows N0067 build, infinite inputs terminated a child process; NaN
  produced a platform-specific string. See
  `tests/reference/sclk-partition/nonfinite-process-windows.json`.
  With an extremely small positive coefficient rate, a finite ET can
  produce a NaN intermediate. The explicit native ET-to-string path covers
  the recorded N0067 partition-selection and zero-field cases on Windows and
  Linux; this is separate from accepting caller-supplied non-finite ticks.
  See `tests/reference/sclk-partition/nan-finite-et/capture.json` for the
  exercised kernels and the limits of this platform-specific evidence.
- Tick/time conversions bound encoded ticks by the rounded accumulated raw
  partition durations. String encoding follows SCENCD endpoint rounding,
  which can differ for fractional endpoints. Clock resets are permitted.
  A map without partition metadata has no declared upper bound.
- `SclkClock` uses the native string path for multiple partitions or a
  nonzero partition start. Its ET-to-string path rounds discrete ticks before
  range checks; continuous `et_to_ticks` retains its separate domain.
  The native reference corpus covers specific MRO and synthetic cases; it
  is not evidence of exhaustive clock/kernel parity.

`DELTET/DELTA_AT` follows NAIF assignment rules: `=` replaces the
accumulated table and `+=` extends it, so a kernel that restates the
leap-second list in a later data block is valid.

## 9. Coordinate scales: TCG and TCB

```rust
use stkcraft_time::convert::utc_to_tai;
use stkcraft_time::coord::{tai_to_tcb, tai_to_tcg, tcb_to_tai, tcg_to_tai};
use stkcraft_time::{Calendar, LeapSecondTable, UtcDateTime};

let lsk = LeapSecondTable::builtin()?;
let utc = UtcDateTime::new(2016, 12, 31, 12, 0, 0.0);
let tai = utc_to_tai(&utc, Calendar::Gregorian, &lsk)?;

let tcg = tai_to_tcg(tai, &lsk);
let tcb = tai_to_tcb(tai, &lsk);

let tai_from_tcg = tcg_to_tai(tcg, &lsk);
let tai_from_tcb = tcb_to_tai(tcb, &lsk);
```

`tai_to_tcb` uses the IAU Fairhead–Bretagnon TDB model, not NAIF `ET`, so
it matches the IAU/SOFA definition of TCB. Both scales are `f64` seconds
near `5e8` at modern epochs; their spacing is about 60 ns.

## 10. Epochs, durations and time series

```rust
use stkcraft_time::{Duration, Epoch, TimeSeries};

let start = Epoch::from_parts(0, 0);
let step = Duration::from_parts(30, 0);
let end = start + Duration::from_parts(90, 0);

let inclusive: Vec<Epoch> = TimeSeries::inclusive(start, end, step).collect();
assert_eq!(inclusive.len(), 4);

let exclusive: Vec<Epoch> = TimeSeries::exclusive(start, end, step).collect();
assert_eq!(exclusive.len(), 3);
```

`Epoch` stores integer TAI seconds plus nanoseconds since
`2000-01-01T00:00:00 TAI`. `Duration` is exact and normalised. Use
`Epoch::checked_from_parts`, `checked_from_tai_seconds`, `checked_add`
and `checked_sub`, or the `Duration::checked_*` methods, for untrusted
input. The infallible constructors and operators panic on overflow or
non-finite input rather than wrapping or returning a fake zero.
`TimeSeries` yields nothing when `step` is zero or negative, and it uses
checked cursor advancement so the last representable epoch is delivered
before iteration ends.

## 11. Formatting

```rust
use stkcraft_time::calendar::Calendar;
use stkcraft_time::format::{
    etcal, iso8601, iso8601_with, rfc2822, rfc3339, spice_calendar, strftime,
    strftime_with, Format, FormatOptions, Formatter,
};
use stkcraft_time::{LeapSecondTable, UtcDateTime};

let utc = UtcDateTime::new(2000, 1, 1, 12, 0, 0.0);

assert_eq!(iso8601(&utc, 3), "2000-01-01T12:00:00.000Z");
assert_eq!(rfc3339(&utc, 9), "2000-01-01T12:00:00.000000000+00:00");
assert_eq!(rfc2822(&utc), "Sat, 01 Jan 2000 12:00:00 +0000");
assert_eq!(spice_calendar(&utc, 3), "2000 JAN 01 12:00:00.000");
assert_eq!(etcal(0.0, 3), "2000 JAN 01 12:00:00.000");

let pattern = strftime(&utc, "%Y-%m-%d %H:%M:%S.%f")?;
let format = Format::parse("%Y-%m-%dT%H:%M:%SZ")?;
let rendered = Formatter::new(&utc, &format).to_string();

// Leap-second and calendar aware formatting.
let lsk = LeapSecondTable::builtin()?;
let options = FormatOptions::new(3)
    .with_calendar(Calendar::Gregorian)
    .with_leap_seconds(&lsk);

let last_second = UtcDateTime::new(2016, 12, 31, 23, 59, 59.9999);
assert_eq!(
    iso8601_with(&last_second, &options),
    "2016-12-31T23:59:60.000Z"
);
assert_eq!(
    strftime_with(&last_second, "%Y-%m-%dT%H:%M:%S", &options)?,
    "2016-12-31T23:59:60"
);
```

Precision is clamped to 9 fractional digits. Rounding is carry-aware:
`59.9999` with precision 3 becomes the next minute, and `60.9999` on a
leap second becomes the next day. `etcal` splits ET into whole days and
seconds before formatting, so microsecond values survive. A non-finite
ET produces `"INVALID ET"`.

Whether a carry crosses a leap second or moves to the next day depends on
the length of the day, so [`FormatOptions`] takes an optional
`LeapSecondTable`. With the table, `23:59:59.9999` on a 86 401-second day
formats as `23:59:60.000`; without it, a 86 400-second day is assumed,
unless the value already has `second >= 60`. Only the final minute of the
day is affected: every other minute still ends at `59.999`, so
`12:34:59.9999` on a leap-second day rounds to `12:35:00.000`. The same
options select the calendar used for the day carry, so a Julian date
rolls from `1500-02-28` to `1500-02-29` rather than to `1500-03-01`. `%j`
and `%a` use the selected calendar as well.

Supported `strftime` tokens: `%Y %y %m %d %e %H %M %S %j %a %A %b %B %z
%Z %f %%`. `%f` is nanoseconds; `%z` is `+0000`; `%Z` is `UTC`. An
unsupported token returns `TimeError::InvalidFormat`.

## 12. Error handling

`TimeError` is the single error type:

| Variant | Meaning |
|---|---|
| `InvalidDate { year, month, day }` | Date not valid for the selected calendar. |
| `InvalidTime { hour, minute }` | Time of day outside its legal range. |
| `InvalidSecond` | Seconds component outside `0.0..61.0`. |
| `InvalidLeapSecond` | `23:59:60.x` without a positive leap second, or `23:59:59.x` on a shortened day. |
| `UtcOutOfRange` | UTC epoch outside the supplied LSK coverage. |
| `Ut1OutOfRange` | Epoch or bracketing EOP sample outside the table. |
| `EopMissing` | Empty EOP table. |
| `EopParse` | EOP text or sample is invalid, including non-finite values. |
| `SclkParse` / `SclkMissing` / `SclkUnsupported` | SCLK text, missing variable, or non-type-1 clock. |
| `SclkPartitionsUnsupported` | Field/string conversion requested for a partitioned clock; encoded ticks↔ET remain usable. |
| `LskParse` / `LskMissing` | LSK text or required `DELTET` variable. |
| `InvalidFormat` | Unsupported `strftime` token. |
| `KernelDateUnsupported` | Unsupported N0067 `@date` literal; never a missing-kernel report. |
| `Overflow` | Reserved for checked arithmetic. |

With the default `std` feature, `TimeError` implements
`std::error::Error`.

## 13. Binaries and tools

The CLI binaries require the `std` feature:

| Binary | Purpose |
|---|---|
| `wgc-compare` | Compare crate results with recorded WebGeocalc values. |
| `ut1-check` | Check UT1 against an IERS EOP table. |
| `tdb-compare` | Compare NAIF and ESA TDB models. |
| `sclk-check` | Check SCLK conversions against CSPICE output. |
| `stkcraft-mcp` | Optional stdio MCP server (`--features mcp`); see `docs/MCP.md`. |

Data-fetching and validation scripts live in `tools/`; the crate itself
never performs network I/O. No EOP or mission SCLK data is embedded at runtime; original mission
SCLK files under tests/kernels are independent test fixtures.

Every download is configurable, so a mirror or a local copy can be used
when the upstream host is slow or blocked:

| Script | Flag | Environment variable | Default |
|---|---|---|---|
| `tools/fetch_eop.py` | `--url` | `STKCRAFT_EOP_URL` | IERS `finals2000A.all` |
| `tools/validate_ut1.py` | `--url` | `STKCRAFT_EOP_URL` | IERS `finals2000A.all` |
| `tools/gen_dtdb_table.py` | `--url` / `--src` | `STKCRAFT_DTDB_URL` | pinned ERFA `dtdb.c` |

`--url` wins over the environment variable, and `--eop` / `--src` skip
the download when they point at an existing file. Downloaded data is
validated on arrival: the EOP file is parsed and summarized, and the
ERFA source is checked against its pinned SHA-256, so a mirror cannot
change the result silently.

## 14. Public API index

This list is enforced, not illustrative: `tests/api_index.rs` parses every
`pub fn`/`struct`/`enum`/`const`/`type`/`trait` in `src/` and fails the
build when an item is missing from this section, or when a name here no
longer exists.

### `calendar`

```rust
pub const J2000_JDN: i64;
pub const GPS_EPOCH_JDN: i64;
pub const GREGORIAN_SWITCH_JDN: i64;

pub enum Calendar { Gregorian, Julian, Mixed }

pub fn is_gregorian_leap(year: i32) -> bool;
pub fn is_julian_leap(year: i32) -> bool;
pub fn days_in_month(year: i32, month: u8, cal: Calendar) -> Option<u8>;
pub fn gregorian_to_jdn(year: i32, month: u8, day: u8) -> i64;
pub fn julian_to_jdn(year: i32, month: u8, day: u8) -> i64;
pub fn jdn_to_gregorian(jdn: i64) -> (i32, u8, u8);
pub fn jdn_to_julian(jdn: i64) -> (i32, u8, u8);
pub fn jdn_to_calendar(jdn: i64, cal: Calendar) -> (i32, u8, u8);
pub fn calendar_to_jdn(year: i32, month: u8, day: u8, cal: Calendar)
    -> Result<i64, TimeError>;
pub fn calendar_to_jd(
    year: i32, month: u8, day: u8, hour: u8, minute: u8, second: f64,
    cal: Calendar,
) -> Result<f64, TimeError>;
pub fn jd_to_mjd(jd: f64) -> f64;
pub fn mjd_to_jd(mjd: f64) -> f64;
```

### `kernel_date`

```rust
pub struct KernelDate {
    pub seconds_past_j2000: f64,
    pub year: i32,
    pub month: u8,
    pub day: u8,
    pub hour: u8,
    pub minute: u8,
    pub second: f64,
}

pub fn parse_kernel_date(text: &str) -> Result<KernelDate, TimeError>;
```

### `epoch`

```rust
pub struct Epoch { /* private fields */ }

impl Epoch {
    pub fn from_parts(sec: i64, nanos: i64) -> Self;
    pub fn checked_from_parts(sec: i64, nanos: i64) -> Option<Self>;
    pub fn from_tai_seconds(seconds: f64) -> Self;
    pub fn checked_from_tai_seconds(seconds: f64) -> Option<Self>;
    pub fn tai_seconds(&self) -> f64;
    pub fn sec(&self) -> i64;
    pub fn nanos(&self) -> u32;
    pub fn checked_add(self, rhs: Duration) -> Option<Self>;
    pub fn checked_sub(self, rhs: Duration) -> Option<Self>;
}

pub struct UtcDateTime {
    pub year: i32,
    pub month: u8,
    pub day: u8,
    pub hour: u8,
    pub minute: u8,
    pub second: f64,
}

impl UtcDateTime {
    pub fn new(year: i32, month: u8, day: u8, hour: u8, minute: u8, second: f64)
        -> Self;
}
```

`Epoch` supports `Add<Duration>`, `Sub<Duration>` and `Sub<Epoch> ->
Duration`.

### `duration`

```rust
pub struct Duration { /* private fields */ }

impl Duration {
    pub const ZERO: Self;
    pub const NANOSECOND: Self;
    pub const SECOND: Self;

    pub fn from_parts(sec: i64, nanos: i64) -> Self;
    pub fn checked_from_parts(sec: i64, nanos: i64) -> Option<Self>;
    pub fn from_nanoseconds(ns: i128) -> Option<Self>;
    pub fn from_seconds_f64(seconds: f64) -> Self;
    pub fn checked_from_seconds_f64(seconds: f64) -> Option<Self>;
    pub fn sec(&self) -> i64;
    pub fn nanos(&self) -> i32;
    pub fn total_nanoseconds(&self) -> i128;
    pub fn seconds_f64(&self) -> f64;
    pub fn is_zero(&self) -> bool;
    pub fn signum(&self) -> i8;
    pub fn abs(&self) -> Self;
    pub fn checked_neg(&self) -> Option<Self>;
    pub fn checked_add(&self, other: Self) -> Option<Self>;
    pub fn checked_sub(&self, other: Self) -> Option<Self>;
    pub fn checked_mul_i64(&self, rhs: i64) -> Option<Self>;
    pub fn floor(&self, step: Self) -> Self;
    pub fn ceil(&self, step: Self) -> Self;
    pub fn round(&self, step: Self) -> Self;
}
```

`Duration` supports `Add`, `Sub`, `Neg`, `Mul<i64>`, `Div<i64>` and
`Display`.

### `leap`

```rust
pub const DELTA_T_A: f64;
pub const K: f64;
pub const EB: f64;
pub const M0: f64;
pub const M1: f64;
pub const JDN_1960: i64;
pub const JDN_1972: i64;

pub struct LeapEntry {
    pub jdn: i64,
    pub delta_at: i32,
}

pub enum LeapSecondSource { IersOnly, Sofa }

pub enum LeapSecondPolicy {
    TableDriven,
    FrozenAfter { jdn: i64 },
}

impl LeapSecondPolicy {
    pub fn frozen_after(year: i32, month: u8, day: u8) -> Self;
}

pub struct LeapSecondTable {
    pub delta_t_a: f64,
    pub k: f64,
    pub eb: f64,
    pub m0: f64,
    pub m1: f64,
}

impl LeapSecondTable {
    pub fn new(entries: Vec<LeapEntry>) -> Result<Self, TimeError>;
    pub fn with_constants(self, delta_t_a: f64, k: f64, eb: f64, m0: f64, m1: f64)
        -> Self;
    pub fn builtin() -> Result<Self, TimeError>;
    pub fn from_lsk(text: &str) -> Result<Self, TimeError>;
    pub fn with_source(self, source: LeapSecondSource) -> Self;
    pub fn source(&self) -> LeapSecondSource;
    pub fn with_policy(self, policy: LeapSecondPolicy) -> Self;
    pub fn policy(&self) -> LeapSecondPolicy;
    pub fn delta_at_f64(&self, jdn: i64, day_fraction: f64) -> Option<f64>;
    pub fn entries(&self) -> &[LeapEntry];
    pub fn coverage(&self) -> (i64, i64);
    pub fn delta_at_for_jdn(&self, jdn: i64) -> Option<i32>;
}

pub fn sofa_delta_at(mjd: f64) -> Option<f64>;
```

`lsk::parse_lsk(text)` and `lsk::builtin()` are equivalent module-level
entry points:

```rust
pub fn parse_lsk(text: &str) -> Result<LeapSecondTable, TimeError>;
pub fn builtin() -> Result<LeapSecondTable, TimeError>;
```

### `convert`

```rust
pub fn utc_to_tai(dt: &UtcDateTime, calendar: Calendar, lsk: &LeapSecondTable)
    -> Result<Epoch, TimeError>;
pub fn tai_to_utc(epoch: Epoch, calendar: Calendar, lsk: &LeapSecondTable)
    -> Result<UtcDateTime, TimeError>;

pub fn tai_to_et(epoch: Epoch, lsk: &LeapSecondTable) -> f64;
pub fn et_to_tai(et: f64, lsk: &LeapSecondTable) -> Epoch;
pub fn tai_to_tt(epoch: Epoch, lsk: &LeapSecondTable) -> f64;
pub fn tt_to_tai(tt: f64, lsk: &LeapSecondTable) -> Epoch;
// In module `wgc_gps`:
pub enum WgcGpsError { InvalidFormat, NonFinite }
pub enum WgcCalendarSystem { Utc, Tdb, Tt, Tdt, Gps }
pub fn gps_seconds_to_week_tow(seconds: f64, lsk: &LeapSecondTable)
    -> Result<String, WgcGpsError>;
pub fn parse_week_tow(input: &str) -> Result<f64, WgcGpsError>;
pub fn gps_seconds_to_et(seconds: f64, lsk: &LeapSecondTable) -> Result<NaifEt, WgcGpsError>;
pub fn week_tow_to_et(input: &str, lsk: &LeapSecondTable) -> Result<NaifEt, WgcGpsError>;
pub fn et_to_gps_display_seconds(et: NaifEt, lsk: &LeapSecondTable) -> Result<f64, WgcGpsError>;
pub fn et_to_utc_calendar_doy(et: NaifEt, lsk: &LeapSecondTable) -> Result<String, ContractError>;
pub fn et_to_calendar_doy(et: NaifEt, system: WgcCalendarSystem, lsk: &LeapSecondTable)
    -> Result<String, ContractError>;
pub fn et_to_calendar_ymd(et: NaifEt, system: WgcCalendarSystem, lsk: &LeapSecondTable)
    -> Result<String, ContractError>;

pub fn tai_to_gps(epoch: Epoch) -> f64;
pub fn gps_to_tai(gps: f64) -> Epoch;

pub fn utc_to_et(dt: &UtcDateTime, calendar: Calendar, lsk: &LeapSecondTable)
    -> Result<f64, TimeError>;
pub fn et_to_utc(et: f64, calendar: Calendar, lsk: &LeapSecondTable)
    -> Result<UtcDateTime, TimeError>;

pub fn ut1_minus_utc(epoch: Epoch, lsk: &LeapSecondTable, eop: &EopTable)
    -> Result<f64, TimeError>;
pub fn tai_to_ut1(epoch: Epoch, lsk: &LeapSecondTable, eop: &EopTable)
    -> Result<f64, TimeError>;
pub fn ut1_to_tai(ut1: f64, lsk: &LeapSecondTable, eop: &EopTable)
    -> Result<Epoch, TimeError>;
pub fn utc_to_ut1(
    dt: &UtcDateTime, calendar: Calendar, lsk: &LeapSecondTable, eop: &EopTable,
) -> Result<f64, TimeError>;
pub fn ut1_to_utc(
    ut1: f64, calendar: Calendar, lsk: &LeapSecondTable, eop: &EopTable,
) -> Result<UtcDateTime, TimeError>;
```

### `eop`

```rust
pub struct EopSample {
    pub mjd: f64,
    pub ut1_minus_utc: f64,
    pub observed: bool,
}

pub enum EopSeries { BulletinA, BulletinB, FinalPreferred }

pub struct EopTable { /* private fields */ }

impl EopTable {
    pub fn new(samples: Vec<EopSample>) -> Result<Self, TimeError>;
    pub fn from_finals2000a(text: &str) -> Result<Self, TimeError>;
    pub fn from_finals2000a_series(text: &str, series: EopSeries)
        -> Result<Self, TimeError>;
    pub fn observed_only(&self) -> Result<Self, TimeError>;
    pub fn ut1_minus_utc(&self, mjd: f64) -> Result<f64, TimeError>;
    pub fn range(&self) -> (f64, f64);
    pub fn samples(&self) -> &[EopSample];
    pub fn len(&self) -> usize;
    pub fn is_empty(&self) -> bool;
}
```

### `sclk`

```rust
pub enum SclkTimeSystem { Tdb, Tdt }

pub struct SclkCoefficient {
    pub ticks: f64,
    pub seconds: f64,
    pub rate: f64,
}

pub struct SclkStringError(/* private */);
impl SclkStringError {
    pub fn spice_short(self) -> &'static str;
}
pub struct SclkStringContext { /* private fields */ }
pub enum NativeSclkError { String(SclkStringError), Native(SclkStringError), Time(TimeError) }

pub struct SclkKernel { /* private fields */ }

impl SclkKernel {
    pub fn parse(text: &str, spacecraft_id: i32) -> Result<Self, TimeError>;
    pub fn decode_native_sclk(&self, ticks: f64) -> Result<String, SclkStringError>;
    pub fn encode_native_sclk(&self, text: &str) -> Result<f64, SclkStringError>;
    pub fn encode_native_sclk_with_context(&self, text: &str, context: &mut SclkStringContext)
        -> Result<f64, SclkStringError>;
    pub fn spacecraft_id(&self) -> i32;
    pub fn data_type(&self) -> i32;
    pub fn time_system(&self) -> SclkTimeSystem;
    pub fn n_fields(&self) -> usize;
    pub fn moduli(&self) -> &[i64];
    pub fn offsets(&self) -> &[i64];
    pub fn coefficients(&self) -> &[SclkCoefficient];
    pub fn partitions(&self) -> (&[f64], &[f64]);
    pub fn ticks_per_msb(&self) -> f64;
    pub fn ticks_from_fields(&self, fields: &[i64]) -> Result<f64, TimeError>;
    pub fn fields_from_ticks(&self, ticks: f64) -> Result<Vec<i64>, TimeError>;
    pub fn parallel_seconds(&self, ticks: f64) -> Result<f64, TimeError>;
    pub fn ticks_from_parallel(&self, seconds: f64) -> Result<f64, TimeError>;
    pub fn ticks_to_et(&self, ticks: f64, lsk: &LeapSecondTable)
        -> Result<f64, TimeError>;
    pub fn et_to_ticks(&self, et: f64, lsk: &LeapSecondTable)
        -> Result<f64, TimeError>;
    pub fn ticks_to_tai(&self, ticks: f64, lsk: &LeapSecondTable)
        -> Result<Epoch, TimeError>;
    pub fn tai_to_ticks(&self, epoch: Epoch, lsk: &LeapSecondTable)
        -> Result<f64, TimeError>;
    pub fn parse_string(&self, sclk: &str) -> Result<Vec<i64>, TimeError>;
    pub fn format_string(&self, fields: &[i64]) -> Result<String, TimeError>;
}

pub trait SclkMap {
    fn sclk_to_et(&self, sclk: &str) -> Result<f64, TimeError>;
    fn et_to_sclk(&self, et: f64) -> Result<String, TimeError>;
}

pub struct SclkClock<'a> {
    pub kernel: &'a SclkKernel,
    pub lsk: &'a LeapSecondTable,
}
impl SclkClock<'_> {
    pub fn native_sclk_to_et(&self, clock: &str) -> Result<f64, NativeSclkError>;
    pub fn native_sclk_to_et_with_context(&self, clock: &str, context: &mut SclkStringContext)
        -> Result<f64, NativeSclkError>;
    pub fn native_et_to_sclk(&self, et: f64) -> Result<String, NativeSclkError>;
}
impl SclkMap for SclkClock<'_>;
```

### `format`

```rust
pub fn iso8601(dt: &UtcDateTime, precision: usize) -> String;
pub fn iso8601_with(dt: &UtcDateTime, options: &FormatOptions<'_>) -> String;
pub fn spice_calendar(dt: &UtcDateTime, precision: usize) -> String;
pub fn spice_calendar_with(dt: &UtcDateTime, options: &FormatOptions<'_>) -> String;
pub fn etcal(et: f64, precision: usize) -> String;
pub fn jd_to_calendar(jd: f64) -> (i32, u8, u8, u8, u8, f64);
pub fn rfc3339(dt: &UtcDateTime, precision: usize) -> String;
pub fn rfc3339_with(dt: &UtcDateTime, options: &FormatOptions<'_>) -> String;
pub fn rfc2822(dt: &UtcDateTime) -> String;
pub fn strftime(dt: &UtcDateTime, pattern: &str) -> Result<String, TimeError>;
pub fn strftime_with(
    dt: &UtcDateTime,
    pattern: &str,
    options: &FormatOptions<'_>,
) -> Result<String, TimeError>;

pub struct FormatOptions<'a> { /* private fields */ }
impl<'a> FormatOptions<'a> {
    pub fn new(precision: usize) -> Self;
    pub fn with_calendar(self, calendar: Calendar) -> Self;
    pub fn with_leap_seconds(self, lsk: &'a LeapSecondTable) -> Self;
    pub fn precision(&self) -> usize;
    pub fn calendar(&self) -> Calendar;
}

pub struct Format { /* private fields */ }
impl Format {
    pub fn parse(pattern: &str) -> Result<Self, TimeError>;
}

pub struct Formatter<'a> { /* private fields */ }
impl<'a> Formatter<'a> {
    pub fn new(dt: &'a UtcDateTime, format: &'a Format) -> Self;
    pub fn with_options(
        dt: &'a UtcDateTime,
        format: &'a Format,
        options: &FormatOptions<'a>,
    ) -> Self;
}
```

`Formatter` implements `core::fmt::Display`.

### `coord`

```rust
pub const L_G: f64;
pub const L_B: f64;
pub const TDB0: f64;

pub fn tcg_minus_tt(epoch: Epoch, lsk: &LeapSecondTable) -> f64;
pub fn tai_to_tcg(epoch: Epoch, lsk: &LeapSecondTable) -> f64;
pub fn tcg_to_tai(tcg: f64, lsk: &LeapSecondTable) -> Epoch;
pub fn tcb_minus_tdb(tdb: f64) -> f64;
pub fn tai_to_tcb(epoch: Epoch, lsk: &LeapSecondTable) -> f64;
pub fn tcb_to_tai(tcb: f64, lsk: &LeapSecondTable) -> Epoch;
```

### `tdb` and `dtdb`

```rust
pub fn tdb_minus_tt_seconds(jd_tt: f64) -> f64;
pub fn tai_to_tdb(epoch: Epoch, lsk: &LeapSecondTable) -> f64;
pub fn tdb_to_tai(tdb: f64, lsk: &LeapSecondTable) -> Epoch;

pub fn dtdb_minus_tt(jd_tt: f64) -> f64;
pub fn dtdb_minus_tt_split(jd1: f64, jd2: f64) -> f64;
pub fn dtdb_minus_tt_at_observer(
    jd1: f64,
    jd2: f64,
    ut1_fraction: f64,
    east_longitude_radians: f64,
    u_km: f64,
    v_km: f64,
) -> Result<f64, DtdbError>;
pub fn tai_to_tdb_iau(epoch: Epoch, lsk: &LeapSecondTable) -> f64;
pub fn tdb_iau_to_tai(tdb: f64, lsk: &LeapSecondTable) -> Epoch;

pub enum DtdbError {
    NonFiniteInput,
    InvalidUt1Fraction,
    InvalidObserverDistance,
    OutsideModelRange,
}
```

### `series` and `timescale`

```rust
pub struct TimeSeries { /* private fields */ }
impl TimeSeries {
    pub fn inclusive(start: Epoch, end: Epoch, step: Duration) -> Self;
    pub fn exclusive(start: Epoch, end: Epoch, step: Duration) -> Self;
}
impl Iterator for TimeSeries { type Item = Epoch; }

pub enum TimeScale {
    Utc, Tai, Tt, Et, Gps, Ut1, Tcg, Tcb,
}
```

### `contract`

```rust
pub enum CalculationProfile { NaifSpice, IauScientific }

#[non_exhaustive]
pub enum ContractError {
    Time(TimeError),
    Scientific(DtdbError),
    NonFinite,
    EpochOutOfRange,
    HistoricalUtcRequiresExplicitModel,
    NaifKernelModelRequired,
    InvalidNaifLeapSeconds,
}

pub struct NaifEt(/* private */);
impl NaifEt {
    pub fn from_seconds(seconds: f64) -> Result<Self, ContractError>;
    pub fn seconds(self) -> f64;
    pub fn profile(self) -> CalculationProfile;
}

pub struct NaifMetadata {
    pub leap_entry_dates: (i64, i64),
    pub leap_source: LeapSecondSource,
    pub leap_policy: LeapSecondPolicy,
    pub deltet: [f64; 5],
}

pub struct NaifJulianUtc(/* private */);
impl NaifJulianUtc {
    pub fn days(self) -> f64;
}

pub struct NaifDeltet {
    pub delta_t_a: f64,
    pub k: f64,
    pub eb: f64,
    pub m0: f64,
    pub m1: f64,
}
pub struct NaifUtcContext<'a> { /* private fields */ }
impl<'a> NaifUtcContext<'a> {
    pub fn from_raw_parts(entries: &'a [LeapEntry], deltet: NaifDeltet)
        -> Result<Self, ContractError>;
    pub fn et_to_spice_julian_utc(self, et: NaifEt)
        -> Result<NaifJulianUtc, ContractError>;
}

pub struct TimeContext<'a> { /* private fields */ }
impl<'a> TimeContext<'a> {
    pub fn new(lsk: &'a LeapSecondTable) -> Self;
    pub fn profile(self) -> CalculationProfile;
    pub fn metadata(self) -> NaifMetadata;
    pub fn to_et(self, epoch: Epoch) -> Result<NaifEt, ContractError>;
    pub fn utc_to_et(self, utc: &UtcDateTime, calendar: Calendar)
        -> Result<NaifEt, ContractError>;
    pub fn to_epoch(self, et: NaifEt) -> Result<Epoch, ContractError>;
    pub fn et_to_utc(self, et: NaifEt, calendar: Calendar)
        -> Result<UtcDateTime, ContractError>;
    pub fn et_to_spice_julian_utc(self, et: NaifEt)
        -> Result<NaifJulianUtc, ContractError>;
}

pub enum ScientificModel {
    GeocentricFairheadBretagnon,
    ObserverFairheadBretagnon,
}

pub struct IauTdb { /* private fields */ }
impl IauTdb {
    pub fn seconds(self) -> f64;
    pub fn model(self) -> ScientificModel;
    pub fn profile(self) -> CalculationProfile;
}

pub struct ScientificContext;
impl ScientificContext {
    pub fn new() -> Self;
    pub fn tt_seconds(self, epoch: Epoch) -> Result<f64, ContractError>;
    pub fn to_tdb(self, epoch: Epoch) -> Result<IauTdb, ContractError>;
    pub fn to_tdb_at_observer(
        self,
        epoch: Epoch,
        ut1_fraction: f64,
        longitude: f64,
        u_km: f64,
        v_km: f64,
    ) -> Result<IauTdb, ContractError>;
}
```

There is no `From<IauTdb>` for `NaifEt`: crossing between the two models
requires an explicit decision. See [`TIME_CONTRACT.md`](TIME_CONTRACT.md).

### `error`

```rust
pub enum TimeError {
    InvalidDate { year: i32, month: u8, day: u8 },
    InvalidTime { hour: u8, minute: u8 },
    InvalidSecond,
    InvalidFormat,
    KernelDateUnsupported,
    EopMissing,
    EopParse,
    SclkParse,
    SclkMissing(&'static str),
    SclkUnsupported,
    SclkPartitionsUnsupported,
    Ut1OutOfRange,
    InvalidLeapSecond,
    UtcOutOfRange,
    LskParse,
    LskMissing(&'static str),
    Overflow,
}
```

### `mcp` (`--features mcp`)

```rust
pub fn run_stdio() -> std::io::Result<()>;
pub fn handle_message(line: &str) -> Option<String>;
pub fn handle_message_with_sclk_context(line: &str, context: &mut SclkStringContext)
    -> Option<String>;
```

`handle_message` is the transport-independent entry point used by the
tests; `run_stdio` reads newline-delimited JSON-RPC from stdin.


## 15. BeiDou and language interfaces

The additive `bdt::Bdt` type implements nominal continuous BDT coordinates
from 2006-01-01 UTC. It provides checked integer parts, total nanoseconds,
full signed week coordinates, UTC conversion with an explicit LSK and ET
conversion through `TimeContext`. Its nominal TAI/BDT offset is not a model
of physical satellite clock corrections. The existing `TimeScale` enum is
unchanged to preserve exhaustive downstream matches.

[Python/WASM/JS support and verification](BINDINGS.md) describes the owned
language objects, precise transport, explicit scientific models, inventory
and packaging. Adapter build requirements are separate from core Rust 1.75.


### `bdt`

```rust
pub const TAI_MINUS_BDT_SECONDS: i64;
pub const GPS_MINUS_BDT_SECONDS: i64;
pub const ORIGIN_TAI_SECONDS: i64;
pub const NANOSECONDS_PER_WEEK: u64;
pub struct Bdt { /* private fields */ }
impl Bdt {
    pub fn checked_from_parts(sec: i64, nanos: i64) -> Option<Self>;
    pub fn checked_from_seconds(seconds: f64) -> Option<Self>;
    pub fn checked_from_nanoseconds(total: i128) -> Option<Self>;
    pub fn sec(self) -> i64;
    pub fn nanos(self) -> u32;
    pub fn seconds(self) -> f64;
    pub fn total_nanoseconds(self) -> i128;
    pub fn from_epoch(epoch: Epoch) -> Result<Self, TimeError>;
    pub fn to_epoch(self) -> Result<Epoch, TimeError>;
    pub fn from_week_nanoseconds(week: i64, nanos: u64) -> Result<Self, TimeError>;
    pub fn week_nanoseconds(self) -> (i64, u64);
    pub fn from_utc(utc: &UtcDateTime, calendar: Calendar, lsk: &LeapSecondTable) -> Result<Self, TimeError>;
    pub fn to_utc(self, calendar: Calendar, lsk: &LeapSecondTable) -> Result<UtcDateTime, TimeError>;
    pub fn from_et(et: NaifEt, context: TimeContext<'_>) -> Result<Self, ContractError>;
    pub fn to_et(self, context: TimeContext<'_>) -> Result<NaifEt, ContractError>;
}
```