matra 0.2.1

NLP library: UDPipe structured parse, base text metrics, summarization, keyphrase extraction. Rust core with Python bindings.
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
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
#![doc = include_str!("../README.md")]

#[cfg(feature = "cli")]
pub mod cli;
pub mod config;
pub mod decompose;
pub mod domain;
pub mod embed;
pub mod extraction;
pub mod hearst;
pub mod metrics;
pub mod nlp;
pub mod source;
mod stopwords;

use std::path::Path;

use decompose::Decomposer;
use domain::{Document, MAX_INPUT_BYTES};
use nlp::NlpProvider;
use source::Source;

/// Reject text whose byte length exceeds [`MAX_INPUT_BYTES`].
///
/// Returns `Error::InputTooLarge { what: "input", .. }` so consumers can
/// distinguish the bound check from per-extractor caps (which use distinct
/// `what` labels). [`Engine::annotate`] runs this gate, and annotate is
/// the only route from text to the parser.
fn check_input_size(text: &str) -> domain::Result<()> {
    if text.len() > MAX_INPUT_BYTES {
        return Err(domain::Error::InputTooLarge {
            limit: MAX_INPUT_BYTES,
            actual: text.len(),
            what: "input",
        });
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// The pipeline surface: Ingest -> Engine
// ---------------------------------------------------------------------------

/// One item of ingested input: a raw document, or the failure that stood
/// in its place.
///
/// The error side is per-document by construction. A failed read does
/// not abort the stream; it travels through the pipeline as data and
/// lands in [`domain::CorpusResult::errors`].
pub type Ingested = std::result::Result<domain::RawDocument, domain::DocumentError>;

enum Pending {
    /// Already in memory. Yielding it cannot fail.
    Ready(domain::RawDocument),
    /// A file to read when pulled.
    File(std::path::PathBuf),
}

/// A stream of documents entering the pipeline.
///
/// One concrete type for every source shape: a string is a stream of
/// one, a file is a stream of one, a directory is a stream of many.
/// That makes "a single document is a collection of one" a fact about
/// the types rather than a convention, and it is why [`Engine::analyze`]
/// can be one function instead of six.
///
/// Reads are lazy. [`Ingest::path`] on a directory lists the entries up
/// front (a listing failure is the constructor's `Err`) but reads no
/// file until the iterator is pulled, so "the constructor returned `Ok`"
/// does not mean "every file was read". Per-file failures surface as
/// `Err` items carrying the path.
pub struct Ingest {
    items: std::vec::IntoIter<Pending>,
}

impl Ingest {
    /// A stream of one in-memory document. Never fails.
    pub fn text(text: impl Into<String>, format: domain::Format) -> Self {
        Self {
            items: vec![Pending::Ready(domain::RawDocument::new(
                text.into(),
                None,
                format,
            ))]
            .into_iter(),
        }
    }

    /// A stream from a path: one document for a file, zero or more for a
    /// directory.
    ///
    /// The `Err` here is top-level only: the path does not exist, or the
    /// directory cannot be listed. Everything per-file (unreadable,
    /// oversized, a symlink) is deferred to iteration and yielded as an
    /// `Err` item, so one bad file cannot abort a directory walk.
    pub fn path(input: impl AsRef<Path>) -> domain::Result<Self> {
        let input = input.as_ref();
        let metadata = std::fs::symlink_metadata(input)?;
        let pending = if metadata.file_type().is_dir() {
            source::directory::DirectorySource
                .candidate_paths(input)?
                .into_iter()
                .map(Pending::File)
                .collect()
        } else {
            // A file, a symlink, or something stranger. FileSource's own
            // guards (symlink refusal, size cap) run at pull time.
            vec![Pending::File(input.to_path_buf())]
        };
        Ok(Self {
            items: pending.into_iter(),
        })
    }
}

impl Iterator for Ingest {
    type Item = Ingested;

    fn next(&mut self) -> Option<Ingested> {
        let item = self.items.next()?;
        Some(match item {
            Pending::Ready(doc) => Ok(doc),
            Pending::File(path) => match source::file::FileSource.read(&path) {
                Ok(docs) => docs.into_iter().next().ok_or_else(|| {
                    domain::DocumentError::new(
                        Some(path),
                        domain::Error::Io(std::io::Error::new(
                            std::io::ErrorKind::InvalidData,
                            "source returned no documents",
                        )),
                    )
                }),
                Err(e) => Err(domain::DocumentError::new(Some(path), e)),
            },
        })
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.items.size_hint()
    }
}

/// The assembled pipeline: an NLP provider plus a decomposer table.
///
/// Construction is the wiring step; after it, analysis is
/// `ingest -> decompose -> compose` with no per-source or per-format
/// entry points. Variation lives in the data ([`Ingest`]'s
/// constructors, the [`decompose::Decomposers`] table), not in the
/// function namespace.
pub struct Engine {
    nlp: Box<dyn NlpProvider>,
    decomposers: decompose::Decomposers,
}

impl Engine {
    /// Wire an engine from a provider and a decomposer table.
    ///
    /// For the table this build ships, pass [`standard_decomposers()`].
    pub fn new(nlp: Box<dyn NlpProvider>, decomposers: decompose::Decomposers) -> Self {
        Self { nlp, decomposers }
    }

    /// Analyze a stream of documents.
    ///
    /// Lazy: nothing is parsed until the returned iterator is pulled,
    /// and each pull runs one document through [`Engine::analyze_one`]
    /// to completion. An `Err` input item passes through unchanged
    /// without touching the pipeline. Collect into
    /// [`domain::CorpusResult`] to partition successes from failures:
    ///
    /// ```no_run
    /// # fn example(engine: &matra::Engine) -> matra::domain::Result<()> {
    /// let result: matra::domain::CorpusResult =
    ///     engine.analyze(matra::Ingest::path("docs/")?).collect();
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// The returned iterator borrows the engine and is not `Send`:
    /// [`NlpProvider`] is `Send` without `Sync`, so the stream cannot be
    /// shared across threads.
    pub fn analyze<I>(
        &self,
        input: I,
    ) -> impl Iterator<Item = std::result::Result<domain::CorpusEntry, domain::DocumentError>>
    where
        I: IntoIterator<Item = Ingested>,
    {
        input
            .into_iter()
            .map(|item| item.and_then(|raw| self.analyze_one(raw)))
    }

    /// Analyze one document: annotate, then compose.
    ///
    /// This is the singleton view of [`Engine::analyze`]; the laws
    /// pinning their agreement live in the test suite.
    pub fn analyze_one(
        &self,
        raw: domain::RawDocument,
    ) -> std::result::Result<domain::CorpusEntry, domain::DocumentError> {
        let path = raw.path.clone();
        match self.annotate(&raw) {
            Ok(mut doc) => {
                self.compose(&mut doc);
                Ok(domain::CorpusEntry::new(path, doc))
            }
            Err(e) => Err(domain::DocumentError::new(path, e)),
        }
    }

    /// Decompose and parse one document into an unmeasured [`Document`]:
    /// structure from the format's decomposer, sentences attached
    /// per-paragraph, every metric slot still `None`.
    ///
    /// This is the only route from text to the parser, which is what
    /// makes the input size cap a property of the pipeline rather than
    /// of each entry point: no text over [`MAX_INPUT_BYTES`] reaches
    /// [`NlpProvider::parse`].
    ///
    /// Structure materializes here (ADR-0008): derived facts whose
    /// detectors live outside the domain are filled onto each parsed
    /// sentence at this choke point. Today that is
    /// [`domain::Sentence::hearst_pairs`], computed by
    /// [`hearst::hypernymy_pairs`]; sentence-level facts whose
    /// detectors live in the domain are computed by `Sentence::new`
    /// inside the provider.
    pub fn annotate(&self, raw: &domain::RawDocument) -> domain::Result<Document> {
        check_input_size(&raw.text)?;
        let decomposer = self
            .decomposers
            .get(&raw.format)
            .ok_or_else(|| domain::Error::UnsupportedFormat(raw.format.clone()))?;
        let mut doc = Document::new(decomposer.decompose(&raw.text));
        for para in doc.paragraphs_mut() {
            if para.in_blockquote {
                continue;
            }
            para.sentences = self.nlp.parse(&para.text)?;
            for sentence in &mut para.sentences {
                sentence.hearst_pairs = hearst::hypernymy_pairs(&sentence.tokens);
            }
        }
        Ok(doc)
    }

    /// Run the metric suite over an annotated document. Total: metrics
    /// read what is attached and skip what is not; there is no failure
    /// path.
    pub fn compose(&self, doc: &mut Document) {
        let suite = metrics::default_suite();
        metrics::run_suite(doc, &suite);
    }
}

#[cfg(feature = "udpipe")]
impl Engine {
    /// Wire the standard pipeline from a resolved [`config::Config`]: the UDPipe
    /// adapter over the configured model directory, plus
    /// [`standard_decomposers()`].
    ///
    /// Additive to [`Engine::new`], which still takes any provider and
    /// any decomposer table. This is the wiring most callers want, named
    /// once instead of rewritten per call site.
    ///
    /// ```no_run
    /// let cfg = matra::config::Config::resolve()?;
    /// let engine = matra::Engine::from_config(&cfg)?;
    /// # Ok::<(), matra::domain::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Whatever [`nlp::udpipe::Udpipe::from_config`] returns: the model
    /// download or its hash verification failed, or the model directory
    /// is not writable.
    pub fn from_config(cfg: &config::Config) -> domain::Result<Engine> {
        let nlp = nlp::udpipe::Udpipe::from_config(cfg)?;
        Ok(Engine::new(Box::new(nlp), standard_decomposers()))
    }

    /// [`Engine::from_config`], with `notice` called once before each
    /// model fetch and not at all when the model is already on disk.
    ///
    /// The route from an application that renders to the adapter that
    /// provisions. A first run downloads 16 MB, and the library writes
    /// to no terminal, so the facts travel out as a
    /// [`domain::ProvisionNotice`] and the caller decides the wording.
    ///
    /// ```no_run
    /// let cfg = matra::config::Config::resolve()?;
    /// let engine = matra::Engine::from_config_with_notice(&cfg, |n| {
    ///     eprintln!("fetching {} into {}", n.artifact, n.destination.display());
    /// })?;
    /// # Ok::<(), matra::domain::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Whatever [`Engine::from_config`] returns.
    pub fn from_config_with_notice(
        cfg: &config::Config,
        notice: impl FnMut(&domain::ProvisionNotice),
    ) -> domain::Result<Engine> {
        let nlp = nlp::udpipe::Udpipe::from_config_with_notice(cfg, notice)?;
        Ok(Engine::new(Box::new(nlp), standard_decomposers()))
    }

    /// [`config::Config::resolve()`] then [`Engine::from_config`]: the no-setup
    /// path, and the only one-liner worth a second name.
    ///
    /// ```no_run
    /// let engine = matra::Engine::with_defaults()?;
    /// # Ok::<(), matra::domain::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Whatever [`config::Config::resolve`] or [`Engine::from_config`] returns.
    pub fn with_defaults() -> domain::Result<Engine> {
        Engine::from_config(&config::Config::resolve()?)
    }
}

/// The decomposer this build ships for `format`, or `None` for formats
/// that are reserved but unimplemented.
///
/// The match is deliberately exhaustive with no wildcard: adding a
/// `Format` variant fails compilation here, so a new format is a
/// conscious registration decision rather than a silent
/// `Error::UnsupportedFormat` at run time.
fn default_decomposer(format: &domain::Format) -> Option<Box<dyn Decomposer>> {
    match format {
        domain::Format::Markdown => Some(Box::new(decompose::markdown::MarkdownDecomposer)),
        domain::Format::PlainText => Some(Box::new(decompose::plain::PlainTextDecomposer)),
        domain::Format::Pdf | domain::Format::Docx => None,
    }
}

/// The decomposer table this build ships: markdown and plain text.
///
/// Lives in the composition root because it is the only place that
/// names every adapter (boundary rule 7). Callers who want a different
/// table build their own with [`decompose::Decomposers::with`].
pub fn standard_decomposers() -> decompose::Decomposers {
    let mut table = decompose::Decomposers::new();
    for format in [
        domain::Format::Markdown,
        domain::Format::PlainText,
        domain::Format::Pdf,
        domain::Format::Docx,
    ] {
        if let Some(decomposer) = default_decomposer(&format) {
            table = table.with(format, decomposer);
        }
    }
    table
}

/// Embed a document's sentences, then cluster them: the one place both
/// halves of the semantic pipeline meet (rule 7). The embedder's own
/// [`identity`](embed::Embedder::identity) travels into the result, so
/// the scores cannot be attributed to a model that did not produce them.
///
/// Sentence text reaching the embedder already passed the pipeline's
/// size cap on its way through `annotate`; no second cap applies here.
///
/// # Errors
///
/// Whatever the embedder returns, plus [`domain::Error::InvalidInput`]
/// if the embedder violates its length contract, plus everything
/// [`extraction::semantic_clusters`] rejects.
pub fn embed_and_cluster(
    doc: &Document,
    embedder: &dyn embed::Embedder,
    threshold: f32,
) -> domain::Result<domain::SemanticClusters> {
    let texts: Vec<&str> = doc.sentences().map(|s| s.text.as_str()).collect();
    // The count cap fires before the expensive stage, not after it: an
    // over-cap document must not run a full embedding pass just to be
    // rejected by the clustering gate. The same check inside
    // `extraction::semantic_clusters` still guards the vectors-in path.
    if texts.len() > extraction::MAX_SEMANTIC_SENTENCES {
        return Err(domain::Error::InputTooLarge {
            limit: extraction::MAX_SEMANTIC_SENTENCES,
            actual: texts.len(),
            what: "semantic_clusters",
        });
    }
    let embeddings = embedder.embed(&texts)?;
    if embeddings.len() != texts.len() {
        return Err(domain::Error::InvalidInput(format!(
            "embedder returned {} vectors for {} sentences, violating its contract",
            embeddings.len(),
            texts.len()
        )));
    }
    extraction::semantic_clusters(&embeddings, threshold, embedder.identity())
}

// ---------------------------------------------------------------------------
// PyO3 bindings (behind "python" feature flag)
// ---------------------------------------------------------------------------

#[cfg(feature = "python")]
mod python {
    use std::path::{Path, PathBuf};

    use pyo3::prelude::*;
    use pyo3::types::{PyAny, PyDict, PyList, PyString};

    use crate::domain;
    use crate::nlp::NlpProvider;

    use domain::{Format, RawDocument};

    /// Routes domain::Error variants to the appropriate Python exception
    /// class, preserving variant identity across the FFI boundary.
    ///
    /// The mapping follows pyo3 conventions: file-not-found maps to
    /// PyFileNotFoundError so Python `try ... except FileNotFoundError`
    /// works as expected; oversized or unsupported inputs are PyValueError;
    /// I/O errors are PyOSError; everything else is PyRuntimeError.
    struct MatraError(domain::Error);

    impl From<domain::Error> for MatraError {
        fn from(e: domain::Error) -> Self {
            MatraError(e)
        }
    }

    impl From<MatraError> for PyErr {
        fn from(e: MatraError) -> PyErr {
            use domain::Error::*;
            use pyo3::exceptions::*;
            let msg = e.0.to_string();
            // domain::Error is #[non_exhaustive] from outside the crate but
            // the compiler sees the full variant set in here, so this match
            // is exhaustive without a wildcard. A new variant will become a
            // compile error — exactly what we want for routing fidelity.
            match e.0 {
                ModelNotFound(_) => PyFileNotFoundError::new_err(msg),
                InputTooLarge { .. } | UnsupportedFormat(_) | InvalidInput(_) => {
                    PyValueError::new_err(msg)
                }
                Io(_) => PyOSError::new_err(msg),
                ModelInvalid(_) | ParseFailed(_) => PyRuntimeError::new_err(msg),
            }
        }
    }

    fn to_dict<'py, T: serde::Serialize>(py: Python<'py>, val: &T) -> PyResult<Bound<'py, PyAny>> {
        pythonize::pythonize(py, val)
            .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))
    }

    /// Holds the assembled pipeline. Create once, reuse across calls.
    ///
    /// Marked unsendable because NLP models may contain C state that is
    /// not thread-safe. Python's GIL provides the necessary synchronization.
    #[pyclass(unsendable)]
    struct Matra {
        engine: crate::Engine,
    }

    impl Matra {
        fn from_nlp(nlp: Box<dyn NlpProvider>) -> Self {
            Self {
                engine: crate::Engine::new(nlp, crate::standard_decomposers()),
            }
        }

        /// One in-memory document through the whole pipeline.
        fn document(&self, text: &str, format: Format) -> Result<domain::Document, MatraError> {
            let raw = RawDocument::new(text.to_string(), None, format);
            self.engine
                .analyze_one(raw)
                .map(|entry| entry.analysis)
                .map_err(|e| MatraError(e.error))
        }

        /// Annotated structure for one in-memory plain-text document.
        ///
        /// Parse only: compose would fill a metric suite the callers of
        /// this helper immediately discard.
        fn annotated(&self, text: &str) -> Result<domain::Document, MatraError> {
            let raw = RawDocument::new(text.to_string(), None, Format::PlainText);
            self.engine.annotate(&raw).map_err(MatraError)
        }

        /// Pipeline-routed sentences for the extractors: same size gate,
        /// same decomposition, same blockquote skipping as `analyze`.
        fn sentences(&self, text: &str) -> Result<Vec<domain::Sentence>, MatraError> {
            Ok(self.annotated(text)?.sentences().cloned().collect())
        }
    }

    #[pymethods]
    impl Matra {
        /// Load a UDPipe model from a local file.
        ///
        /// The argument is anything Python calls a path: a `str`, or an
        /// object implementing `os.PathLike` such as a `pathlib.Path`.
        #[staticmethod]
        #[cfg(feature = "udpipe")]
        fn from_path(model_path: PathBuf) -> PyResult<Self> {
            let nlp = crate::nlp::udpipe::Udpipe::from_path(model_path).map_err(MatraError)?;
            Ok(Self::from_nlp(Box::new(nlp)))
        }

        /// Download (if absent) and load the English UDPipe model.
        ///
        /// With no argument the directory is resolved through
        /// `Config`: `MATRA_MODEL_DIR`, else the data root's `models`
        /// subdirectory, else a pre-existing `~/.matra/models`.
        ///
        /// A directory given explicitly is anything Python calls a path:
        /// a `str`, or an `os.PathLike` such as a `pathlib.Path`.
        #[staticmethod]
        #[cfg(feature = "udpipe")]
        #[pyo3(signature = (model_dir=None))]
        fn english(model_dir: Option<PathBuf>) -> PyResult<Self> {
            let nlp = match model_dir {
                Some(dir) => crate::nlp::udpipe::Udpipe::english(dir),
                None => {
                    let cfg = crate::config::Config::resolve().map_err(MatraError)?;
                    crate::nlp::udpipe::Udpipe::from_config(&cfg)
                }
            }
            .map_err(MatraError)?;
            Ok(Self::from_nlp(Box::new(nlp)))
        }

        /// Analyze plain text. Returns a Python dict.
        fn analyze<'py>(&self, py: Python<'py>, text: &str) -> PyResult<Bound<'py, PyAny>> {
            let analysis = self.document(text, Format::PlainText)?;
            to_dict(py, &analysis)
        }

        /// Analyze markdown. Returns a Python dict.
        fn analyze_markdown<'py>(
            &self,
            py: Python<'py>,
            text: &str,
        ) -> PyResult<Bound<'py, PyAny>> {
            let analysis = self.document(text, Format::Markdown)?;
            to_dict(py, &analysis)
        }

        /// TF-IDF extractive summary. Returns a list of dicts.
        fn tfidf_summarize<'py>(
            &self,
            py: Python<'py>,
            text: &str,
            n: usize,
        ) -> PyResult<Bound<'py, PyAny>> {
            let sentences = self.sentences(text)?;
            let result = crate::extraction::tfidf_summarize(&sentences, n).map_err(MatraError)?;
            to_dict(py, &result)
        }

        /// TextRank extractive summary. Returns a list of dicts.
        fn textrank_summarize<'py>(
            &self,
            py: Python<'py>,
            text: &str,
            n: usize,
        ) -> PyResult<Bound<'py, PyAny>> {
            let sentences = self.sentences(text)?;
            let result =
                crate::extraction::textrank_summarize(&sentences, n).map_err(MatraError)?;
            to_dict(py, &result)
        }

        /// RAKE keyphrase extraction. Returns a list of dicts.
        fn rake_keyphrases<'py>(
            &self,
            py: Python<'py>,
            text: &str,
            max_phrases: usize,
        ) -> PyResult<Bound<'py, PyAny>> {
            let sentences = self.sentences(text)?;
            let result =
                crate::extraction::rake_keyphrases(&sentences, max_phrases).map_err(MatraError)?;
            to_dict(py, &result)
        }

        /// YAKE keyphrase extraction. Returns a list of dicts.
        fn yake_keyphrases<'py>(
            &self,
            py: Python<'py>,
            text: &str,
            max_phrases: usize,
        ) -> PyResult<Bound<'py, PyAny>> {
            let sentences = self.sentences(text)?;
            let result =
                crate::extraction::yake_keyphrases(&sentences, max_phrases).map_err(MatraError)?;
            to_dict(py, &result)
        }

        /// Parse plain text, embed its sentences with `model`, and
        /// cluster them at `threshold`. Returns the serialized
        /// `SemanticClusters` as a dict.
        ///
        /// `model` is any Python object with `embed` and `identity`,
        /// `Model2Vec` included. Anything that is not the built-in
        /// adapter is wrapped in [`PyEmbedder`], which needs only the
        /// `embed` port, so a build without the `model2vec` feature
        /// still accepts a caller's own embedder.
        ///
        /// The embedder is settled before the parse runs. Wrapping reads
        /// `identity()`, and an object that cannot name its geometry is
        /// refused there; doing that first costs one method call instead
        /// of a whole document's parse.
        fn semantic_clusters<'py>(
            &self,
            py: Python<'py>,
            text: &str,
            threshold: f32,
            model: &Bound<'py, PyAny>,
        ) -> PyResult<Bound<'py, PyAny>> {
            // Fast path: the built-in adapter is used directly, so the
            // embedding route makes no Python call at all.
            #[cfg(feature = "model2vec")]
            if let Ok(loaded) = model.cast::<Model2Vec>() {
                let doc = self.annotated(text)?;
                let result = crate::embed_and_cluster(&doc, &loaded.get().inner, threshold)
                    .map_err(MatraError)?;
                return to_dict(py, &result);
            }
            let embedder = PyEmbedder::new(model)?;
            let doc = self.annotated(text)?;
            let result =
                crate::embed_and_cluster(&doc, &embedder, threshold).map_err(MatraError)?;
            to_dict(py, &result)
        }

        /// Analyze every document a path names: one for a file, one per
        /// regular file for a directory.
        ///
        /// Returns a list in ingestion order (sorted by path for a
        /// directory). Each item is a `CorpusEntry` dict for a document
        /// that analyzed, or a `DocumentError` dict for one that did
        /// not, so one unreadable file is one error item rather than an
        /// aborted walk. A failure listing the path itself is raised
        /// instead: there is no per-document result to carry it.
        ///
        /// `path` is anything Python calls a path: a `str`, or an
        /// `os.PathLike` such as a `pathlib.Path`.
        ///
        /// Both item shapes are assembled here rather than serialized.
        /// `CorpusEntry` is `Serialize`, but its `path` is a `PathBuf`,
        /// and serde refuses a non-UTF-8 one: a single file with an
        /// undecodable name would end the whole walk with a
        /// `RuntimeError`, which is the failure this method exists to
        /// prevent. Every path here goes through [`fs_path_str`]
        /// instead, and only the `Document` is serialized.
        fn analyze_path<'py>(&self, py: Python<'py>, path: PathBuf) -> PyResult<Bound<'py, PyAny>> {
            let ingest = crate::Ingest::path(&path).map_err(MatraError)?;
            let items = PyList::empty(py);
            for item in self.engine.analyze(ingest) {
                let entry = match item {
                    Ok(entry) => corpus_entry_dict(py, &entry)?,
                    Err(err) => document_error_dict(py, &err)?,
                };
                items.append(entry)?;
            }
            Ok(items.into_any())
        }
    }

    /// A loaded static embedding model (model2vec artifact format).
    /// Tier 2: its vectors are model opinion, and everything derived from
    /// them carries this model's identity (ADR-0010).
    #[cfg(feature = "model2vec")]
    #[pyclass(frozen)]
    struct Model2Vec {
        inner: crate::embed::model2vec::Model2Vec,
    }

    #[cfg(feature = "model2vec")]
    #[pymethods]
    impl Model2Vec {
        /// Load from a directory holding model.safetensors,
        /// tokenizer.json, and config.json. No network is touched.
        ///
        /// The argument is anything Python calls a path: a `str`, or an
        /// `os.PathLike` such as a `pathlib.Path`.
        #[staticmethod]
        fn from_dir(dir: PathBuf) -> PyResult<Self> {
            let inner = crate::embed::model2vec::Model2Vec::from_dir(dir).map_err(MatraError)?;
            Ok(Self { inner })
        }

        /// Download (if absent) and load the pinned reference embedding
        /// model, verifying its three-file digest against a constant in
        /// the source before anything is loaded.
        ///
        /// Only files this call downloads are ever removed. A directory
        /// already holding all three artifacts under a different digest,
        /// or holding only some of them, is refused without anything
        /// being downloaded over or deleted.
        ///
        /// With no argument the directory is resolved through `Config`:
        /// the model directory joined with the configured embedding
        /// model name. A directory given explicitly is anything Python
        /// calls a path: a `str`, or an `os.PathLike` such as a
        /// `pathlib.Path`.
        #[staticmethod]
        #[pyo3(signature = (dir=None))]
        fn potion_base_8m(dir: Option<PathBuf>) -> PyResult<Self> {
            let inner = match dir {
                Some(dir) => crate::embed::model2vec::Model2Vec::potion_base_8m(dir),
                None => {
                    let cfg = crate::config::Config::resolve().map_err(MatraError)?;
                    crate::embed::model2vec::Model2Vec::from_config(&cfg)
                }
            }
            .map_err(MatraError)?;
            Ok(Self { inner })
        }

        /// SHA-256 over the three artifact files, the identity carried
        /// into every result derived from this model's vectors.
        #[getter]
        fn model_hash(&self) -> &str {
            self.inner.model_hash()
        }

        /// Number of dimensions of every vector this model produces.
        #[getter]
        fn dimensions(&self) -> usize {
            self.inner.dimensions()
        }

        /// The geometry this model's vectors live in, as the `Embedder`
        /// protocol asks for it: the same string `model_hash` carries.
        ///
        /// It is a method, not a getter, because the protocol a caller's
        /// own object satisfies declares a method. With it, `Model2Vec`
        /// satisfies that protocol rather than merely being accepted
        /// alongside it, and one annotation covers both.
        fn identity(&self) -> String {
            self.inner.model_hash().to_string()
        }

        /// Embed each text into a vector. One vector per text, in
        /// order, all of `dimensions` length.
        fn embed(&self, texts: Vec<String>) -> PyResult<Vec<Vec<f32>>> {
            use crate::embed::Embedder;
            let refs: Vec<&str> = texts.iter().map(String::as_str).collect();
            let out = self.inner.embed(&refs).map_err(MatraError)?;
            Ok(out.into_iter().map(|e| e.0).collect())
        }
    }

    /// Cluster caller-supplied embedding vectors at `threshold`,
    /// attributing the scores to `model_hash`. The vectors-in twin of
    /// `Matra.semantic_clusters` for consumers who already hold
    /// embeddings; indices in the result are positions in `embeddings`.
    #[pyfunction]
    #[allow(unreachable_pub)] // pyo3 macro requirement, same as _core below.
    pub fn semantic_clusters<'py>(
        py: Python<'py>,
        embeddings: Vec<Vec<f32>>,
        threshold: f32,
        model_hash: &str,
    ) -> PyResult<Bound<'py, PyAny>> {
        let embeddings: Vec<domain::Embedding> =
            embeddings.into_iter().map(domain::Embedding).collect();
        let result = crate::extraction::semantic_clusters(&embeddings, threshold, model_hash)
            .map_err(MatraError)?;
        to_dict(py, &result)
    }

    /// Run the matra command line and return its exit code.
    ///
    /// `argv` is the argument vector *without* the program name, which
    /// `cli::run` supplies itself so `--help` reads the same from this
    /// launcher and from the Rust binary.
    ///
    /// The command renders into byte buffers, which are then written to
    /// Python's own `sys.stdout` and `sys.stderr` and flushed. Handing
    /// `cli::run` the real file descriptors would interleave badly with
    /// anything Python has already buffered on the same stream; going
    /// through `sys` keeps one writer per stream.
    ///
    /// A failure writing those buffers out is swallowed rather than
    /// raised. It is a broken pipe in practice (`matra ... | head`), and
    /// the Rust launcher treats that as success too; there is nowhere
    /// left to report it to in any case.
    ///
    /// The arguments arrive as arbitrary Python objects and go through
    /// `os.fsencode`, not through `String`. A `sys.argv` entry is not
    /// guaranteed to be text: on unix a path is bytes, and Python decodes
    /// an undecodable one with surrogate escapes rather than failing.
    /// Extracting a `String` would reject exactly those arguments, so a
    /// file the Rust binary opens without comment would be unreachable
    /// through this launcher. `os.fsencode` reverses the escape and hands
    /// back the original bytes, which become an `OsString` unchanged. A
    /// conversion failure is raised rather than swallowed: an argument
    /// that is not a string, bytes, or a path is a caller's error, and
    /// silently dropping it would run a different command than the one
    /// that was asked for.
    #[pyfunction]
    #[allow(unreachable_pub)] // pyo3 macro requirement, same as _core below.
    pub fn cli_main(py: Python<'_>, argv: Vec<Bound<'_, PyAny>>) -> PyResult<i32> {
        use std::ffi::OsString;

        let fsencode = py.import("os")?.getattr("fsencode")?;
        let mut args: Vec<OsString> = Vec::with_capacity(argv.len() + 1);
        args.push(OsString::from("matra"));
        for arg in argv {
            let bytes: Vec<u8> = fsencode.call1((arg,))?.extract()?;
            args.push(os_string_of(bytes));
        }

        // stdout is buffered and written at the end, so the rendered
        // result arrives as one piece. stderr is written through as it
        // is produced, because the first thing a cold run writes there
        // is "downloading the model", and a diagnostic that explains a
        // twenty-second wait is worthless once the wait is over.
        let mut out: Vec<u8> = Vec::new();
        let mut err = PyStream { py, name: "stderr" };
        let code = crate::cli::run(args, &mut out, &mut err);

        let _ = write_stream(py, "stdout", &out);
        Ok(i32::from(code))
    }

    /// A [`std::io::Write`] that forwards each write straight to a `sys`
    /// stream instead of accumulating it.
    ///
    /// The GIL is held for the whole of `cli_main`, so calling back into
    /// Python here is the same access the surrounding function already
    /// has.
    struct PyStream<'py> {
        py: Python<'py>,
        name: &'static str,
    }

    impl std::io::Write for PyStream<'_> {
        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
            write_stream(self.py, self.name, buf)
                .map(|()| buf.len())
                .map_err(|e| std::io::Error::other(e.to_string()))
        }

        /// `write_stream` flushes the Python stream on every write, so
        /// there is nothing held here to flush.
        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }

    /// The bytes `os.fsencode` produced, as an `OsString`.
    ///
    /// On unix an `OsString` is bytes and the filesystem is bytes, so
    /// this is exact: the argument reaches `cli::run` as the same bytes
    /// `std::env::args_os` would have delivered to the Rust binary.
    #[cfg(unix)]
    fn os_string_of(bytes: Vec<u8>) -> std::ffi::OsString {
        use std::os::unix::ffi::OsStringExt;
        std::ffi::OsString::from_vec(bytes)
    }

    /// Elsewhere there is no lossless byte route into an `OsString`, so
    /// an argument that is not valid UTF-8 loses the offending bytes to
    /// the replacement character rather than reaching the command line
    /// intact. Naming the limit here is the honest version of it.
    #[cfg(not(unix))]
    fn os_string_of(bytes: Vec<u8>) -> std::ffi::OsString {
        std::ffi::OsString::from(String::from_utf8_lossy(&bytes).into_owned())
    }

    /// Write one rendered buffer to the named `sys` stream and flush it.
    fn write_stream(py: Python<'_>, name: &str, bytes: &[u8]) -> PyResult<()> {
        if bytes.is_empty() {
            return Ok(());
        }
        let stream = py.import("sys")?.getattr(name)?;
        // The renderers only emit UTF-8; `from_utf8_lossy` is the belt to
        // that suspenders, so a surprise byte degrades one character
        // rather than losing the whole run's output.
        stream.call_method1("write", (String::from_utf8_lossy(bytes).as_ref(),))?;
        stream.call_method0("flush")?;
        Ok(())
    }

    /// A Python object standing in for an [`Embedder`](crate::embed::Embedder).
    ///
    /// The port is a trait, so the extension point was already there;
    /// this is the adapter that lets a Python object reach it. A caller
    /// who has embeddings from a service, a cache, or a library matra
    /// does not ship passes an object with `embed` and `identity` and
    /// gets the same clustering the built-in adapter gets.
    ///
    /// [`Embedder`](crate::embed::Embedder) requires `Send`. The object
    /// is held as `Py<PyAny>`, which is `Send` because it carries no GIL
    /// attachment: it is a reference the interpreter owns, not a pointer
    /// into interpreter state. Every access below re-attaches with
    /// [`Python::attach`] before touching it, so moving this value
    /// between threads never moves an attachment with it.
    ///
    /// The identity is read once, at construction. The trait's promise
    /// is that an identity names one geometry, and a Python object could
    /// return a different string on every call; reading it once keeps
    /// the promise on the object's behalf rather than trusting it.
    struct PyEmbedder {
        obj: Py<PyAny>,
        identity: String,
    }

    impl PyEmbedder {
        /// Wrap `obj`, reading its `identity()` now.
        ///
        /// # Errors
        ///
        /// `ValueError` if `identity()` is missing, raises, or returns
        /// something other than a string.
        fn new(obj: &Bound<'_, PyAny>) -> PyResult<Self> {
            let raw = obj.call_method0("identity").map_err(|e| {
                MatraError(domain::Error::InvalidInput(format!(
                    "calling identity() on the embedder failed: {e}"
                )))
            })?;
            let identity = raw.extract::<String>().map_err(|e| {
                MatraError(domain::Error::InvalidInput(format!(
                    "the embedder's identity() must return a str: {e}"
                )))
            })?;
            Ok(Self {
                obj: obj.clone().unbind(),
                identity,
            })
        }
    }

    impl crate::embed::Embedder for PyEmbedder {
        fn embed(&self, texts: &[&str]) -> domain::Result<Vec<domain::Embedding>> {
            Python::attach(|py| {
                let returned = self
                    .obj
                    .bind(py)
                    .call_method1("embed", (texts.to_vec(),))
                    .map_err(|e| {
                        domain::Error::InvalidInput(format!("the embedder's embed() raised {e}"))
                    })?;
                // Two stages rather than one `Vec<Vec<f64>>` extraction,
                // so the message names which level of the shape was
                // wrong and which vector went astray.
                let rows = returned.extract::<Vec<Bound<'_, PyAny>>>().map_err(|e| {
                    domain::Error::InvalidInput(format!(
                        "the embedder's embed() must return a sequence of vectors: {e}"
                    ))
                })?;
                rows.iter()
                    .enumerate()
                    .map(|(i, row)| {
                        // Python floats are f64 and matra's carrier is
                        // f32, so every vector narrows here. The count
                        // and dimension contract is checked once, in
                        // `embed_and_cluster` and `semantic_clusters`,
                        // and is not restated here.
                        let values = row.extract::<Vec<f64>>().map_err(|e| {
                            domain::Error::InvalidInput(format!(
                                "the embedder's embed() returned a vector at index {i} that is not a sequence of numbers: {e}"
                            ))
                        })?;
                        Ok(domain::Embedding(
                            values.into_iter().map(|v| v as f32).collect(),
                        ))
                    })
                    .collect()
            })
        }

        fn identity(&self) -> &str {
            &self.identity
        }
    }

    /// A path as the `str` Python itself would name it by.
    ///
    /// serde refuses a non-UTF-8 `Path`, and a file whose name is not
    /// valid UTF-8 is exactly the file a corpus walk has to report on.
    /// So the bytes go through `os.fsdecode`, which is Python's own
    /// filesystem decoding: an undecodable byte becomes a surrogate
    /// escape rather than an error or a replacement character, and
    /// `os.fsencode` on the result hands back the bytes this path came
    /// from. A caller can open what the walk names.
    #[cfg(unix)]
    fn fs_path_str<'py>(py: Python<'py>, path: &Path) -> PyResult<Bound<'py, PyString>> {
        use std::os::unix::ffi::OsStrExt;

        let bytes = pyo3::types::PyBytes::new(py, path.as_os_str().as_bytes());
        let decoded = py.import("os")?.getattr("fsdecode")?.call1((bytes,))?;
        Ok(decoded.cast_into::<PyString>()?)
    }

    /// Elsewhere there is no lossless byte route out of an `OsStr`, the
    /// same limit `os_string_of` names on the way in, so an undecodable
    /// name loses the offending bytes to the replacement character
    /// rather than round-tripping.
    #[cfg(not(unix))]
    fn fs_path_str<'py>(py: Python<'py>, path: &Path) -> PyResult<Bound<'py, PyString>> {
        Ok(PyString::new(py, &path.to_string_lossy()))
    }

    /// The `path` field of either corpus item: a `str` for a document
    /// that came from disk, `None` for one that never did.
    fn fs_path_item<'py>(
        py: Python<'py>,
        path: Option<&Path>,
    ) -> PyResult<Option<Bound<'py, PyString>>> {
        path.map(|p| fs_path_str(py, p)).transpose()
    }

    /// Project a [`domain::CorpusEntry`] into a dict.
    ///
    /// Assembled field by field rather than serialized whole, because
    /// serde would refuse the `PathBuf` on a non-UTF-8 name and take the
    /// analysis down with it. The `Document` still goes through serde:
    /// it is the shape `analyze` returns, and there is one wire form of
    /// it, not two.
    fn corpus_entry_dict<'py>(
        py: Python<'py>,
        entry: &domain::CorpusEntry,
    ) -> PyResult<Bound<'py, PyAny>> {
        let item = PyDict::new(py);
        item.set_item("path", fs_path_item(py, entry.path.as_deref())?)?;
        item.set_item("analysis", to_dict(py, &entry.analysis)?)?;
        Ok(item.into_any())
    }

    /// Project a [`domain::DocumentError`] into a dict.
    ///
    /// `DocumentError` is deliberately not `Serialize`: it wraps
    /// `domain::Error`, which wraps `std::io::Error`, and no stable wire
    /// shape exists for that. The two fields are materialized instead,
    /// the error as the `kind` [`domain::Error::kind`] names plus the
    /// `Display` text a human reads.
    fn document_error_dict<'py>(
        py: Python<'py>,
        err: &domain::DocumentError,
    ) -> PyResult<Bound<'py, PyAny>> {
        let error = PyDict::new(py);
        error.set_item("kind", err.error.kind())?;
        error.set_item("message", err.error.to_string())?;

        let item = PyDict::new(py);
        item.set_item("path", fs_path_item(py, err.path.as_deref())?)?;
        item.set_item("error", error)?;
        Ok(item.into_any())
    }

    #[pymodule]
    #[allow(unreachable_pub)] // pyo3's #[pymodule] macro requires pub fn even when the module is private.
    pub fn _core(m: &Bound<'_, PyModule>) -> PyResult<()> {
        m.add_class::<Matra>()?;
        #[cfg(feature = "model2vec")]
        m.add_class::<Model2Vec>()?;
        m.add_function(pyo3::wrap_pyfunction!(semantic_clusters, m)?)?;
        m.add_function(pyo3::wrap_pyfunction!(cli_main, m)?)?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::nlp::NlpProvider;
    use domain::Section;

    /// Minimal NlpProvider that returns no sentences. Lets us test composition-root
    /// gates (input size, etc.) without requiring a real NLP backend.
    struct EmptyNlp;
    impl NlpProvider for EmptyNlp {
        fn parse(&self, _text: &str) -> domain::Result<Vec<domain::Sentence>> {
            Ok(Vec::new())
        }
    }

    /// Splits the input on `.` and returns one [`Sentence`] per non-empty
    /// piece. Tokens are not constructed (the pipeline tests below only
    /// look at sentence text and counts). Lets us assert the
    /// per-paragraph parse contract without a real NLP backend.
    struct DotSplitNlp;
    impl NlpProvider for DotSplitNlp {
        fn parse(&self, text: &str) -> domain::Result<Vec<domain::Sentence>> {
            Ok(text
                .split('.')
                .map(str::trim)
                .filter(|s| !s.is_empty())
                .map(|s| domain::Sentence::new(s.to_string(), Vec::new()))
                .collect())
        }
    }

    use std::sync::atomic::{AtomicUsize, Ordering};

    /// DotSplitNlp that counts parse calls and records the largest text
    /// it was handed, through a handle the test keeps. Refuses any text
    /// containing the marker. Lets the law tests observe exactly when
    /// (and with what) the pipeline reaches the parser, even though the
    /// engine owns the provider.
    struct ObservableNlp {
        calls: std::sync::Arc<AtomicUsize>,
        max_len_seen: std::sync::Arc<AtomicUsize>,
    }
    impl ObservableNlp {
        fn new() -> (
            Self,
            std::sync::Arc<AtomicUsize>,
            std::sync::Arc<AtomicUsize>,
        ) {
            let calls = std::sync::Arc::new(AtomicUsize::new(0));
            let max_len = std::sync::Arc::new(AtomicUsize::new(0));
            (
                Self {
                    calls: calls.clone(),
                    max_len_seen: max_len.clone(),
                },
                calls,
                max_len,
            )
        }
    }
    impl NlpProvider for ObservableNlp {
        fn parse(&self, text: &str) -> domain::Result<Vec<domain::Sentence>> {
            self.calls.fetch_add(1, Ordering::SeqCst);
            self.max_len_seen.fetch_max(text.len(), Ordering::SeqCst);
            if text.contains("POISON") {
                return Err(domain::Error::ParseFailed("poisoned".to_string()));
            }
            DotSplitNlp.parse(text)
        }
    }

    fn law_engine() -> Engine {
        Engine::new(Box::new(DotSplitNlp), standard_decomposers())
    }

    /// Structural fingerprint for law equality: serialized entries plus
    /// stringified errors. `Document` has no `PartialEq`; serde is the
    /// comparison it does have.
    fn fingerprint(
        results: Vec<std::result::Result<domain::CorpusEntry, domain::DocumentError>>,
    ) -> Vec<String> {
        results
            .into_iter()
            .map(|r| match r {
                Ok(entry) => format!("ok:{}", serde_json::to_string(&entry).unwrap()),
                Err(e) => format!("err:{e}"),
            })
            .collect()
    }

    fn raw_plain(text: &str) -> domain::RawDocument {
        domain::RawDocument::new(text.to_string(), None, domain::Format::PlainText)
    }

    #[test]
    fn law_l1_analyze_commutes_with_chain() {
        let engine = law_engine();
        let a = || Ingest::text("First stream. Has two.", domain::Format::PlainText);
        let b = || Ingest::text("Second stream here.", domain::Format::PlainText);

        let chained: Vec<_> = engine.analyze(a().chain(b())).collect();
        let separate: Vec<_> = engine.analyze(a()).chain(engine.analyze(b())).collect();
        assert_eq!(fingerprint(chained), fingerprint(separate));
    }

    #[test]
    fn law_l2_analyze_of_empty_is_empty() {
        let engine = law_engine();
        assert_eq!(engine.analyze(std::iter::empty()).count(), 0);
    }

    #[test]
    fn law_l3_analyze_commutes_with_singleton_injection() {
        let engine = law_engine();
        let raw = || raw_plain("One document. Two sentences.");

        let streamed: Vec<_> = engine.analyze(std::iter::once(Ok(raw()))).collect();
        let direct: Vec<_> = std::iter::once(engine.analyze_one(raw())).collect();
        assert_eq!(fingerprint(streamed), fingerprint(direct));
    }

    #[test]
    fn law_l4_analyze_one_is_annotate_then_compose() {
        let engine = law_engine();
        let raw = raw_plain("Composed of parts. Checked by law.");

        let via_analyze_one = engine.analyze_one(raw.clone()).unwrap().analysis;
        let via_stages = {
            let mut doc = engine.annotate(&raw).unwrap();
            engine.compose(&mut doc);
            doc
        };
        assert_eq!(
            serde_json::to_string(&via_analyze_one).unwrap(),
            serde_json::to_string(&via_stages).unwrap()
        );
    }

    #[test]
    fn law_l5_partition_entries_plus_errors_equals_input() {
        let (nlp, _, _) = ObservableNlp::new();
        let engine = Engine::new(Box::new(nlp), standard_decomposers());
        let input: Vec<Ingested> = vec![
            Ok(raw_plain("Good document one.")),
            Ok(raw_plain("This one is POISON and fails.")),
            Err(domain::DocumentError::new(
                Some(std::path::PathBuf::from("lost.md")),
                domain::Error::ParseFailed("upstream".to_string()),
            )),
            Ok(raw_plain("Good document two.")),
        ];
        let n = input.len();
        let result: domain::CorpusResult = engine.analyze(input).collect();
        assert_eq!(result.corpus.entries.len() + result.errors.len(), n);
        assert_eq!(result.corpus.entries.len(), 2);
        assert_eq!(result.errors.len(), 2);
    }

    #[test]
    fn law_l6_err_input_passes_through_untouched() {
        let (nlp, calls, _) = ObservableNlp::new();
        let engine = Engine::new(Box::new(nlp), standard_decomposers());
        let input: Vec<Ingested> = vec![Err(domain::DocumentError::new(
            Some(std::path::PathBuf::from("ghost.md")),
            domain::Error::ParseFailed("upstream".to_string()),
        ))];

        let out: Vec<_> = engine.analyze(input).collect();
        assert_eq!(out.len(), 1);
        let err = out.into_iter().next().unwrap().unwrap_err();
        assert_eq!(err.path, Some(std::path::PathBuf::from("ghost.md")));
        assert_eq!(err.to_string(), "ghost.md: parse failed: upstream");
        assert_eq!(
            calls.load(Ordering::SeqCst),
            0,
            "an Err input item must not reach the parser"
        );
    }

    #[test]
    fn law_l6_err_input_never_reaches_the_parser() {
        // Same law, observed from the provider's side: an all-Err stream
        // produces zero parse calls, and a control document afterwards
        // proves the counter is live.
        let (nlp, calls, _) = ObservableNlp::new();
        let engine = Engine::new(Box::new(nlp), standard_decomposers());
        let input: Vec<Ingested> = (0..3)
            .map(|i| {
                Err(domain::DocumentError::new(
                    None,
                    domain::Error::ParseFailed(format!("e{i}")),
                ))
            })
            .collect();
        let _ = engine.analyze(input).count();
        assert_eq!(calls.load(Ordering::SeqCst), 0);

        engine.annotate(&raw_plain("Control.")).unwrap();
        assert_eq!(calls.load(Ordering::SeqCst), 1, "counter is live");
    }

    #[test]
    fn law_l7_no_oversized_text_reaches_the_parser() {
        let (nlp, _, max_len) = ObservableNlp::new();
        let engine = Engine::new(Box::new(nlp), standard_decomposers());
        let oversized = "a".repeat(MAX_INPUT_BYTES + 1);

        // Through the stream.
        let out: Vec<_> = engine
            .analyze(Ingest::text(oversized.clone(), domain::Format::PlainText))
            .collect();
        assert!(matches!(
            out[0].as_ref().unwrap_err().error,
            domain::Error::InputTooLarge { .. }
        ));

        // Through annotate directly.
        let raw = raw_plain(&oversized);
        assert!(matches!(
            engine.annotate(&raw),
            Err(domain::Error::InputTooLarge { .. })
        ));

        assert!(
            max_len.load(Ordering::SeqCst) <= MAX_INPUT_BYTES,
            "the parser never saw text over the cap"
        );
    }

    #[test]
    fn annotate_rejects_unregistered_format() {
        let engine = law_engine();
        let raw = domain::RawDocument::new("text".to_string(), None, domain::Format::Pdf);
        assert!(matches!(
            engine.annotate(&raw),
            Err(domain::Error::UnsupportedFormat(domain::Format::Pdf))
        ));
    }

    #[test]
    fn annotate_leaves_metrics_none_and_compose_fills_them() {
        let engine = law_engine();
        let raw = raw_plain("Annotate attaches structure. Compose measures it.");
        let mut doc = engine.annotate(&raw).unwrap();
        assert!(doc.vocabulary_ttr.is_none(), "annotate does not measure");
        assert!(doc.passive_ratio.is_none(), "annotate does not measure");
        assert!(doc.total_sentences() > 0, "annotate does attach");
        engine.compose(&mut doc);
        // DotSplitNlp builds token-less sentences, so token-derived
        // document metrics stay None here; what compose guarantees is
        // totality, which is the absence of a failure path in its
        // signature. passive_ratio is sentence-derived, so it does
        // fill: no sentence here has a passive construction.
        assert_eq!(
            doc.passive_ratio,
            Some(0.0),
            "compose fills the sentence-derived aggregate"
        );
    }

    #[test]
    fn annotate_fills_hearst_pairs_at_the_choke_point() {
        /// Returns one sentence carrying the verified "Animals such as
        /// dogs" arc shape for any input, so the test can observe the
        /// pipeline running the detector without a real model.
        struct SuchAsNlp;
        impl NlpProvider for SuchAsNlp {
            fn parse(&self, _text: &str) -> domain::Result<Vec<domain::Sentence>> {
                let tok = |id: usize, text: &str, lemma: &str, pos: &str, dep: &str, head| {
                    domain::Token::builder(
                        id,
                        text.to_string(),
                        lemma.to_string(),
                        pos.to_string(),
                        head,
                        dep.to_string(),
                    )
                    .build()
                };
                Ok(vec![domain::Sentence::new(
                    "Animals such as dogs bark".to_string(),
                    vec![
                        tok(1, "Animals", "animal", "NOUN", "nsubj", 5),
                        tok(2, "such", "such", "ADJ", "case", 4),
                        tok(3, "as", "as", "ADP", "fixed", 2),
                        tok(4, "dogs", "dog", "NOUN", "nmod", 1),
                        tok(5, "bark", "bark", "VERB", "root", 0),
                    ],
                )])
            }
        }

        let engine = Engine::new(Box::new(SuchAsNlp), standard_decomposers());
        let doc = engine.annotate(&raw_plain("any text")).unwrap();
        let sentence = doc.sentences().next().expect("one sentence");
        assert_eq!(sentence.hearst_pairs.len(), 1, "annotate ran the detector");
        let pair = &sentence.hearst_pairs[0];
        assert_eq!(pair.pattern, domain::HearstPattern::SuchAs);
        assert_eq!(pair.hypernym.head_id, 1);
        assert_eq!(pair.hyponym.head_id, 4);
    }

    #[test]
    fn ingest_text_is_a_stream_of_one() {
        let items: Vec<_> = Ingest::text("hello", domain::Format::PlainText).collect();
        assert_eq!(items.len(), 1);
        let doc = items.into_iter().next().unwrap().unwrap();
        assert_eq!(doc.text, "hello");
        assert_eq!(doc.path, None);
    }

    #[test]
    fn ingest_path_file_is_a_stream_of_one() {
        let dir = tempfile::tempdir().unwrap();
        let f = dir.path().join("one.md");
        std::fs::write(&f, "# One").unwrap();
        let items: Vec<_> = Ingest::path(&f).unwrap().collect();
        assert_eq!(items.len(), 1);
        let doc = items.into_iter().next().unwrap().unwrap();
        assert_eq!(doc.path.as_deref(), Some(f.as_path()));
        assert!(matches!(doc.format, domain::Format::Markdown));
    }

    #[test]
    fn ingest_path_directory_streams_sorted_entries() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("b.txt"), "B").unwrap();
        std::fs::write(dir.path().join("a.md"), "# A").unwrap();
        let items: Vec<_> = Ingest::path(dir.path()).unwrap().collect();
        assert_eq!(items.len(), 2);
        let paths: Vec<_> = items
            .into_iter()
            .map(|r| r.unwrap().path.unwrap())
            .collect();
        assert!(paths[0].ends_with("a.md"));
        assert!(paths[1].ends_with("b.txt"));
    }

    #[test]
    fn ingest_path_missing_is_a_constructor_error() {
        assert!(Ingest::path("/definitely/not/here").is_err());
    }

    #[cfg(unix)]
    #[test]
    fn ingest_per_file_failure_is_an_err_item_not_an_abort() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("good.md"), "# Good").unwrap();
        let bad = dir.path().join("bad.md");
        std::fs::write(&bad, "# Bad").unwrap();
        std::fs::set_permissions(&bad, std::fs::Permissions::from_mode(0o000)).unwrap();

        let items: Vec<_> = Ingest::path(dir.path()).unwrap().collect();
        let _ = std::fs::set_permissions(&bad, std::fs::Permissions::from_mode(0o644));

        assert_eq!(items.len(), 2);
        assert_eq!(items.iter().filter(|r| r.is_ok()).count(), 1);
        let err = items.into_iter().find_map(|r| r.err()).unwrap();
        assert!(err.path.unwrap().ends_with("bad.md"));
    }

    #[test]
    fn standard_decomposers_cover_exactly_the_shipping_formats() {
        let table = standard_decomposers();
        assert!(table.get(&domain::Format::Markdown).is_some());
        assert!(table.get(&domain::Format::PlainText).is_some());
        assert!(
            table.get(&domain::Format::Pdf).is_none(),
            "Pdf is reserved, not shipped"
        );
        assert!(
            table.get(&domain::Format::Docx).is_none(),
            "Docx is reserved, not shipped"
        );
    }

    #[test]
    fn input_at_cap_is_accepted() {
        // "a" repeated MAX_INPUT_BYTES times = exactly the cap.
        let engine = Engine::new(Box::new(EmptyNlp), standard_decomposers());
        let raw = raw_plain(&"a".repeat(MAX_INPUT_BYTES));
        assert!(
            engine.annotate(&raw).is_ok(),
            "input exactly at cap should be accepted"
        );
    }

    #[test]
    fn input_one_byte_over_cap_is_rejected() {
        let engine = Engine::new(Box::new(EmptyNlp), standard_decomposers());
        let raw = raw_plain(&"a".repeat(MAX_INPUT_BYTES + 1));
        match engine.annotate(&raw) {
            Err(domain::Error::InputTooLarge {
                limit,
                actual,
                what,
            }) => {
                assert_eq!(limit, MAX_INPUT_BYTES);
                assert_eq!(actual, MAX_INPUT_BYTES + 1);
                assert_eq!(what, "input");
            }
            other => panic!("expected InputTooLarge, got {other:?}"),
        }
    }

    #[test]
    fn parse_per_paragraph_scopes_sentences_to_originating_paragraph() {
        // FM1 regression: two paragraphs with the same first 30 chars.
        // Pre-fix, attach_sentences would prefix-match and could assign
        // either paragraph's first sentence to the wrong paragraph
        // (and silently drop the other). Per-paragraph parse makes the
        // assignment unambiguous by construction.
        let text = "The system processes input now. Tail one.\n\n\
                    The system processes input now. Tail two.";
        let analysis = law_engine().analyze_one(raw_plain(text)).unwrap().analysis;

        let paras: Vec<_> = analysis.paragraphs().collect();
        assert_eq!(paras.len(), 2);
        assert_eq!(paras[0].sentences.len(), 2);
        assert_eq!(paras[1].sentences.len(), 2);

        // Each paragraph keeps its own tail; no leak.
        assert!(paras[0].sentences.iter().any(|s| s.text.contains("one")));
        assert!(paras[1].sentences.iter().any(|s| s.text.contains("two")));
        assert!(!paras[0].sentences.iter().any(|s| s.text.contains("two")));
        assert!(!paras[1].sentences.iter().any(|s| s.text.contains("one")));
    }

    #[test]
    fn parse_per_paragraph_no_inner_substring_theft() {
        // Inner-substring regression: paragraph A contains paragraph B's
        // first-sentence prefix as a mid-text substring. Pre-fix, the
        // greedy prefix-contains check could steal B's sentence into A.
        // Per-paragraph parse makes the question moot.
        let text = "Outer talks about the special phrase processes input now. End A.\n\n\
                    The special phrase processes input now. End B.";
        let analysis = law_engine().analyze_one(raw_plain(text)).unwrap().analysis;

        let paras: Vec<_> = analysis.paragraphs().collect();
        assert_eq!(paras.len(), 2);

        // Paragraph A should have its own two sentences; paragraph B its own two.
        // Critically: B's "End B" must be in B, not stolen by A.
        assert!(paras[1].sentences.iter().any(|s| s.text.contains("End B")));
        assert!(!paras[0].sentences.iter().any(|s| s.text.contains("End B")));
    }

    #[test]
    fn empty_paragraph_followed_by_valid_paragraph() {
        // Trailing whitespace on an empty paragraph used to confuse the
        // prefix-match wiring; per-paragraph parse handles cleanly.
        // PlainTextDecomposer collapses runs of blank lines, so this
        // registers a custom decomposer that injects an empty paragraph,
        // which also exercises a caller-built table end to end.
        struct InjectEmptyParagraph;
        impl Decomposer for InjectEmptyParagraph {
            fn decompose(&self, text: &str) -> Vec<Section> {
                let mut sections = decompose::plain::PlainTextDecomposer.decompose(text);
                if let Some(section) = sections.first_mut() {
                    section
                        .paragraphs
                        .insert(0, domain::Paragraph::new(String::new(), false));
                }
                sections
            }
        }

        let table = decompose::Decomposers::new()
            .with(domain::Format::PlainText, Box::new(InjectEmptyParagraph));
        let engine = Engine::new(Box::new(DotSplitNlp), table);
        let analysis = engine
            .analyze_one(raw_plain("Real content sentence.\n\nAnother real one."))
            .unwrap()
            .analysis;

        let paras: Vec<_> = analysis.paragraphs().collect();
        assert_eq!(paras.len(), 3);
        assert_eq!(
            paras[0].sentences.len(),
            0,
            "empty paragraph has zero sentences"
        );
        assert!(!paras[1].sentences.is_empty());
        assert!(!paras[2].sentences.is_empty());
    }

    // ------------------------------------------------------------------
    // embed_and_cluster: the composition root's pairing of the halves
    // ------------------------------------------------------------------

    /// Mock embedder: a fixed vector per call, optionally lying about
    /// the count to violate the length contract.
    struct FixedEmbedder {
        identity: &'static str,
        /// When set, return this many vectors regardless of input.
        force_count: Option<usize>,
    }
    impl embed::Embedder for FixedEmbedder {
        fn embed(&self, texts: &[&str]) -> domain::Result<Vec<domain::Embedding>> {
            let n = self.force_count.unwrap_or(texts.len());
            Ok((0..n).map(|_| domain::Embedding(vec![1.0, 0.0])).collect())
        }
        fn identity(&self) -> &str {
            self.identity
        }
    }

    fn two_sentence_doc() -> Document {
        let engine = Engine::new(Box::new(DotSplitNlp), standard_decomposers());
        let raw = domain::RawDocument::new(
            "One sentence. Another sentence.".to_string(),
            None,
            domain::Format::PlainText,
        );
        engine.annotate(&raw).expect("annotate")
    }

    #[test]
    fn embed_and_cluster_carries_the_embedder_identity() {
        let doc = two_sentence_doc();
        let embedder = FixedEmbedder {
            identity: "the-real-model",
            force_count: None,
        };
        let out = embed_and_cluster(&doc, &embedder, 0.9).expect("cluster");
        assert_eq!(out.model_hash, "the-real-model");
        // Identical vectors cluster together, sanity of the plumbing.
        assert_eq!(out.clusters.len(), 1);
    }

    #[test]
    fn embed_and_cluster_rejects_a_length_contract_violation() {
        let doc = two_sentence_doc();
        let embedder = FixedEmbedder {
            identity: "liar",
            force_count: Some(1),
        };
        match embed_and_cluster(&doc, &embedder, 0.9) {
            Err(domain::Error::InvalidInput(msg)) => {
                assert!(msg.contains("violating its contract"));
            }
            other => panic!("expected InvalidInput, got {:?}", other.map(|_| ())),
        }
    }

    #[test]
    fn embed_and_cluster_caps_before_embedding() {
        /// An embedder that panics if reached: the cap must fire first.
        struct MustNotEmbed;
        impl embed::Embedder for MustNotEmbed {
            fn embed(&self, _texts: &[&str]) -> domain::Result<Vec<domain::Embedding>> {
                panic!("embed ran on an over-cap document");
            }
            fn identity(&self) -> &str {
                "unreached"
            }
        }
        let many = "Word. ".repeat(extraction::MAX_SEMANTIC_SENTENCES + 1);
        let engine = Engine::new(Box::new(DotSplitNlp), standard_decomposers());
        let raw = domain::RawDocument::new(many, None, domain::Format::PlainText);
        let doc = engine.annotate(&raw).expect("annotate");
        match embed_and_cluster(&doc, &MustNotEmbed, 0.9) {
            Err(domain::Error::InputTooLarge { what, .. }) => {
                assert_eq!(what, "semantic_clusters");
            }
            other => panic!("expected InputTooLarge, got {:?}", other.map(|_| ())),
        }
    }
}