tracecite-docs 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,787 @@
1
+ """Canonical table normalisation and deterministic retrieval text."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ from collections import Counter
8
+ from collections.abc import Iterable, Mapping
9
+ from datetime import date, datetime
10
+ from hashlib import sha256
11
+ from itertools import pairwise
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from ._text import (
16
+ cell_unit,
17
+ collapse_space,
18
+ escape_pipe_cell,
19
+ header_unit,
20
+ is_missing,
21
+ is_pipe_table_start,
22
+ normalise_label,
23
+ slug,
24
+ split_pipe_row,
25
+ strip_caption_id,
26
+ )
27
+ from .models import (
28
+ NormalisedTable,
29
+ SourceFormat,
30
+ TableContext,
31
+ TableDiagnostic,
32
+ TableNormalisationError,
33
+ source_hash,
34
+ )
35
+ from .pandoc import ParsedPandocTable, parse_pandoc_tables
36
+
37
+ _METADATA_RE = re.compile(
38
+ r"<!--\s*(?:knowledge-table|tracecite-table)\s*:\s*(\{.*?\})\s*-->", re.DOTALL
39
+ )
40
+ _ORDINALS = {"index", "order", "position", "rank", "row"}
41
+ _DIRECTION_RE = re.compile(r"(.+?)\s+(ascending|descending)\b", re.IGNORECASE)
42
+ _NUMBER_RE = re.compile(r"^\s*[-+]?\d[\d,]*(?:\.\d+)?(?:[eE][-+]?\d+)?")
43
+ _ISO_DATE_RE = re.compile(r"^\d{4}-\d{2}-\d{2}(?:[T ].*)?$")
44
+
45
+
46
+ def normalise_pandoc_table(
47
+ source: str,
48
+ *,
49
+ context: TableContext | None = None,
50
+ strict: bool = False,
51
+ pandoc: str | Path | None = None,
52
+ allow_pipe_fallback: bool = False,
53
+ ) -> NormalisedTable:
54
+ """Normalise exactly one Pandoc Markdown table.
55
+
56
+ Pandoc is authoritative. The reduced fallback is limited to ordinary pipe
57
+ tables and is used only when explicitly requested.
58
+ """
59
+
60
+ context = context or TableContext()
61
+ metadata = _merged_metadata(source, context.metadata)
62
+ parse_diagnostics: list[TableDiagnostic] = _pipe_source_diagnostics(source)
63
+
64
+ try:
65
+ parsed_tables = parse_pandoc_tables(source, pandoc=pandoc)
66
+ except (FileNotFoundError, TableNormalisationError) as error:
67
+ if not allow_pipe_fallback:
68
+ raise
69
+ parsed_tables = [_parse_pipe_fallback(source)]
70
+ parse_diagnostics.append(
71
+ TableDiagnostic(
72
+ "table.pipe-fallback",
73
+ "warning",
74
+ f"Pandoc was unavailable or rejected the source; reduced pipe-table parsing was used: {error}",
75
+ )
76
+ )
77
+
78
+ if len(parsed_tables) != 1:
79
+ raise TableNormalisationError(
80
+ f"normalise_pandoc_table expects exactly one table; found {len(parsed_tables)}"
81
+ )
82
+
83
+ return normalise_parsed_table(
84
+ parsed_tables[0],
85
+ raw_source=source,
86
+ context=context,
87
+ metadata=metadata,
88
+ extra_diagnostics=parse_diagnostics,
89
+ strict=strict,
90
+ )
91
+
92
+
93
+ def normalise_parsed_table(
94
+ parsed: ParsedPandocTable,
95
+ *,
96
+ raw_source: str,
97
+ context: TableContext,
98
+ metadata: Mapping[str, Any] | None = None,
99
+ source_format: SourceFormat = "pandoc-markdown",
100
+ extra_diagnostics: Iterable[TableDiagnostic] = (),
101
+ strict: bool = False,
102
+ ) -> NormalisedTable:
103
+ """Build the public normal form from an already parsed Pandoc table."""
104
+
105
+ metadata = dict(metadata or {})
106
+ labels = _string_map(metadata.get("labels"))
107
+ units = _string_map(metadata.get("units"))
108
+ row_identity = _string_list(metadata.get("row_identity"))
109
+ description = _optional_text(metadata.get("description"))
110
+ ordering = context.ordering or _optional_text(metadata.get("ordering"))
111
+
112
+ raw_headers = [collapse_space(value) for value in parsed.headers]
113
+ headers = [labels.get(header, header) for header in raw_headers]
114
+ rows = [[collapse_space(value) for value in row] for row in parsed.rows]
115
+
116
+ caption = context.caption or parsed.caption or description
117
+ table_id = (
118
+ context.table_id
119
+ or parsed.table_id
120
+ or _optional_text(metadata.get("table_id"))
121
+ or _stable_table_id(
122
+ caption, context.section_path, context.document_path, headers
123
+ )
124
+ )
125
+
126
+ diagnostics = [*parsed.diagnostics, *extra_diagnostics]
127
+ diagnostics.extend(
128
+ _validate_table(
129
+ headers=headers,
130
+ raw_headers=raw_headers,
131
+ rows=rows,
132
+ units=units,
133
+ ordering=ordering,
134
+ row_identity=row_identity,
135
+ )
136
+ )
137
+
138
+ canonical = _canonical_markdown(
139
+ headers=headers,
140
+ rows=rows,
141
+ alignments=parsed.alignments,
142
+ caption=caption,
143
+ table_id=table_id,
144
+ )
145
+ normalised_text, row_ids, row_records = _render_retrieval_text(
146
+ table_id=table_id,
147
+ caption=caption,
148
+ section_path=context.section_path,
149
+ document_path=context.document_path,
150
+ source_code_path=context.source_code_path,
151
+ headers=headers,
152
+ raw_headers=raw_headers,
153
+ rows=rows,
154
+ units=units,
155
+ ordering=ordering,
156
+ description=description,
157
+ row_identity=row_identity,
158
+ )
159
+
160
+ supported = not any(
161
+ item.severity == "error" and item.code.startswith("table.unsupported")
162
+ for item in diagnostics
163
+ )
164
+ merged_metadata = {
165
+ **metadata,
166
+ "labels": labels,
167
+ "units": units,
168
+ "row_identity": row_identity,
169
+ "raw_headers": raw_headers,
170
+ }
171
+ if ordering:
172
+ merged_metadata["ordering"] = ordering
173
+ if description:
174
+ merged_metadata["description"] = description
175
+
176
+ result = NormalisedTable(
177
+ table_id=table_id,
178
+ caption=caption,
179
+ section_path=context.section_path,
180
+ headers=tuple(headers),
181
+ rows=tuple(tuple(row) for row in rows),
182
+ raw_source=raw_source,
183
+ source_format=source_format,
184
+ canonical_markdown=canonical,
185
+ normalised_text=normalised_text,
186
+ row_ids=tuple(row_ids),
187
+ row_records=tuple(row_records),
188
+ diagnostics=tuple(diagnostics),
189
+ document_path=context.document_path,
190
+ source_code_path=context.source_code_path,
191
+ source_hash=source_hash(raw_source, context),
192
+ supported=supported,
193
+ source_start_line=_optional_int(metadata.get("source_start_line")),
194
+ source_end_line=_optional_int(metadata.get("source_end_line")),
195
+ metadata=merged_metadata,
196
+ )
197
+ if strict and result.has_errors:
198
+ errors = [item.message for item in diagnostics if item.severity == "error"]
199
+ raise TableNormalisationError(
200
+ f"Table {table_id} failed strict normalisation: " + "; ".join(errors)
201
+ )
202
+ return result
203
+
204
+
205
+ def _render_retrieval_text(
206
+ *,
207
+ table_id: str,
208
+ caption: str | None,
209
+ section_path: tuple[str, ...],
210
+ document_path: str,
211
+ source_code_path: str | None,
212
+ headers: list[str],
213
+ raw_headers: list[str],
214
+ rows: list[list[str]],
215
+ units: Mapping[str, str],
216
+ ordering: str | None,
217
+ description: str | None,
218
+ row_identity: list[str],
219
+ ) -> tuple[str, list[str], list[str]]:
220
+ title = caption or description or (section_path[-1] if section_path else table_id)
221
+ context_lines = [f"Table: {title}", f"Table identifier: {table_id}"]
222
+ if document_path and document_path != "<memory>":
223
+ context_lines.append(f"Source document: {document_path}")
224
+ if source_code_path:
225
+ context_lines.append(f"Executable source: {source_code_path}")
226
+ if section_path:
227
+ context_lines.append(f"Section: {' > '.join(section_path)}")
228
+ if description and description != title:
229
+ context_lines.append(f"Description: {description}")
230
+ if ordering:
231
+ context_lines.append(f"Ordering: {ordering}")
232
+ if row_identity:
233
+ context_lines.append(f"Row identity columns: {'; '.join(row_identity)}")
234
+ context_lines.append(f"Columns: {'; '.join(headers)}")
235
+ context_text = " ".join(_sentence(line) for line in context_lines)
236
+
237
+ ordinal = _ordinal_index(headers)
238
+ row_ids: list[str] = []
239
+ row_records: list[str] = []
240
+ row_paragraphs: list[str] = []
241
+ for number, row in enumerate(rows, start=1):
242
+ row_name = f"Row {number}"
243
+ if ordinal is not None and ordinal < len(row) and not is_missing(row[ordinal]):
244
+ row_name = f"{headers[ordinal]} {row[ordinal]}"
245
+
246
+ fields: list[str] = []
247
+ for index, (header, raw_header, value) in enumerate(
248
+ zip(headers, raw_headers, row, strict=True)
249
+ ):
250
+ if index == ordinal:
251
+ continue
252
+ rendered = "not available" if is_missing(value) else value
253
+ unit = units.get(raw_header) or units.get(header)
254
+ if (
255
+ unit
256
+ and rendered != "not available"
257
+ and not cell_unit(rendered)
258
+ and unit not in header
259
+ ):
260
+ rendered = f"{rendered} {unit}"
261
+ fields.append(f"{header}: {rendered}")
262
+
263
+ sentence = _sentence(f"{row_name}. " + "; ".join(fields))
264
+ row_id = _row_id(
265
+ table_id=table_id,
266
+ headers=headers,
267
+ row=row,
268
+ row_identity=row_identity,
269
+ )
270
+ row_paragraphs.append(sentence)
271
+ row_ids.append(row_id)
272
+ row_records.append(context_text + " " + sentence)
273
+
274
+ if not rows:
275
+ row_paragraphs.append("This table contains no data rows.")
276
+
277
+ return (
278
+ "\n".join(context_lines) + "\n\n" + "\n\n".join(row_paragraphs),
279
+ row_ids,
280
+ row_records,
281
+ )
282
+
283
+
284
+ def _validate_table(
285
+ *,
286
+ headers: list[str],
287
+ raw_headers: list[str],
288
+ rows: list[list[str]],
289
+ units: Mapping[str, str],
290
+ ordering: str | None,
291
+ row_identity: list[str],
292
+ ) -> list[TableDiagnostic]:
293
+ diagnostics: list[TableDiagnostic] = []
294
+ normalised_headers = [normalise_label(value) for value in headers]
295
+
296
+ duplicates = sorted(
297
+ value for value, count in Counter(normalised_headers).items() if count > 1
298
+ )
299
+ if duplicates:
300
+ diagnostics.append(
301
+ TableDiagnostic(
302
+ "table.duplicate-headers",
303
+ "error",
304
+ "Duplicate headers after normalisation: " + ", ".join(duplicates),
305
+ )
306
+ )
307
+
308
+ if not rows:
309
+ diagnostics.append(
310
+ TableDiagnostic(
311
+ "table.empty-body", "warning", "The table contains no data rows."
312
+ )
313
+ )
314
+
315
+ seen_rows: set[tuple[str, ...]] = set()
316
+ duplicate_rows = 0
317
+ for row in rows:
318
+ key = tuple(row)
319
+ if key in seen_rows:
320
+ duplicate_rows += 1
321
+ seen_rows.add(key)
322
+ if duplicate_rows:
323
+ diagnostics.append(
324
+ TableDiagnostic(
325
+ "table.duplicate-rows",
326
+ "warning",
327
+ f"The table contains {duplicate_rows} duplicated data row(s).",
328
+ )
329
+ )
330
+
331
+ ordinal = _ordinal_index(headers)
332
+ if ordinal is not None:
333
+ values = [row[ordinal].strip() for row in rows]
334
+ present = [value for value in values if value]
335
+ if len(present) != len(set(present)):
336
+ diagnostics.append(
337
+ TableDiagnostic(
338
+ "table.duplicate-rank",
339
+ "error",
340
+ f'Ordinal column "{headers[ordinal]}" contains duplicate values.',
341
+ column=ordinal + 1,
342
+ )
343
+ )
344
+ numeric = [_number(value) for value in present]
345
+ if present and all(value is not None for value in numeric):
346
+ numbers = [float(value) for value in numeric if value is not None]
347
+ if numbers != sorted(numbers):
348
+ diagnostics.append(
349
+ TableDiagnostic(
350
+ "table.nonmonotonic-rank",
351
+ "warning",
352
+ f'Ordinal column "{headers[ordinal]}" is not monotonic ascending.',
353
+ column=ordinal + 1,
354
+ )
355
+ )
356
+
357
+ header_lookup = {
358
+ normalise_label(header): index for index, header in enumerate(headers)
359
+ }
360
+ identity_indices: list[int] = []
361
+ for identity in row_identity:
362
+ index = header_lookup.get(normalise_label(identity))
363
+ if index is None:
364
+ diagnostics.append(
365
+ TableDiagnostic(
366
+ "table.missing-row-identity-column",
367
+ "error",
368
+ f'Configured row identity column "{identity}" is not present.',
369
+ )
370
+ )
371
+ else:
372
+ identity_indices.append(index)
373
+
374
+ if row_identity and len(identity_indices) == len(row_identity):
375
+ seen_identity: dict[tuple[str, ...], int] = {}
376
+ for row_number, row in enumerate(rows, start=1):
377
+ key = tuple(row[index].strip() for index in identity_indices)
378
+ missing_columns = [
379
+ headers[index]
380
+ for index, value in zip(identity_indices, key, strict=True)
381
+ if is_missing(value)
382
+ ]
383
+ if missing_columns:
384
+ diagnostics.append(
385
+ TableDiagnostic(
386
+ "table.missing-row-identity-value",
387
+ "error",
388
+ "Configured row identity contains a missing value in: "
389
+ + ", ".join(missing_columns),
390
+ row=row_number,
391
+ )
392
+ )
393
+ continue
394
+ previous = seen_identity.get(key)
395
+ if previous is not None:
396
+ diagnostics.append(
397
+ TableDiagnostic(
398
+ "table.duplicate-row-identity",
399
+ "error",
400
+ f"Rows {previous} and {row_number} have the same configured row identity.",
401
+ row=row_number,
402
+ )
403
+ )
404
+ else:
405
+ seen_identity[key] = row_number
406
+
407
+ diagnostics.extend(_unit_diagnostics(headers, raw_headers, rows, units))
408
+ if ordering:
409
+ diagnostic = _ordering_diagnostic(headers, rows, ordering)
410
+ if diagnostic:
411
+ diagnostics.append(diagnostic)
412
+ return diagnostics
413
+
414
+
415
+ def _unit_diagnostics(
416
+ headers: list[str],
417
+ raw_headers: list[str],
418
+ rows: list[list[str]],
419
+ units: Mapping[str, str],
420
+ ) -> list[TableDiagnostic]:
421
+ diagnostics: list[TableDiagnostic] = []
422
+ for column, (header, raw_header) in enumerate(
423
+ zip(headers, raw_headers, strict=True)
424
+ ):
425
+ declared = units.get(raw_header) or units.get(header) or header_unit(header)
426
+ header_declared = header_unit(header)
427
+ if (
428
+ declared
429
+ and header_declared
430
+ and _unit_key(declared) != _unit_key(header_declared)
431
+ ):
432
+ diagnostics.append(
433
+ TableDiagnostic(
434
+ "table.header-unit-conflict",
435
+ "warning",
436
+ f'Column "{header}" declares conflicting units "{header_declared}" and "{declared}".',
437
+ column=column + 1,
438
+ )
439
+ )
440
+
441
+ observed: dict[str, str] = {}
442
+ for row_number, row in enumerate(rows, start=1):
443
+ unit = cell_unit(row[column]) if column < len(row) else None
444
+ if unit:
445
+ unit_key = _unit_key(unit)
446
+ observed.setdefault(unit_key, unit)
447
+ if declared and _unit_key(unit) != _unit_key(declared):
448
+ diagnostics.append(
449
+ TableDiagnostic(
450
+ "table.unit-conflict",
451
+ "warning",
452
+ f'Column "{header}" declares "{declared}" but row {row_number} contains "{unit}".',
453
+ row=row_number,
454
+ column=column + 1,
455
+ )
456
+ )
457
+ if len(observed) > 1:
458
+ labels = sorted(observed.values(), key=str.casefold)
459
+ diagnostics.append(
460
+ TableDiagnostic(
461
+ "table.mixed-units",
462
+ "warning",
463
+ f'Column "{header}" contains mixed explicit units: {", ".join(labels)}.',
464
+ column=column + 1,
465
+ )
466
+ )
467
+ return diagnostics
468
+
469
+
470
+ def _ordering_diagnostic(
471
+ headers: list[str],
472
+ rows: list[list[str]],
473
+ ordering: str,
474
+ ) -> TableDiagnostic | None:
475
+ clauses = []
476
+ for match in _DIRECTION_RE.finditer(ordering.replace(" then ", ", ")):
477
+ phrase = match.group(1).split(",")[-1].strip(" ,")
478
+ direction = match.group(2).lower()
479
+ index = _match_header(phrase, headers)
480
+ if index is not None:
481
+ clauses.append((index, direction))
482
+
483
+ if not clauses:
484
+ return TableDiagnostic(
485
+ "table.ordering-unchecked",
486
+ "info",
487
+ f'Ordering metadata could not be matched conservatively to a column: "{ordering}".',
488
+ )
489
+ if len(rows) < 2:
490
+ return None
491
+
492
+ if any(_compare_rows(left, right, clauses) > 0 for left, right in pairwise(rows)):
493
+ return TableDiagnostic(
494
+ "table.ordering-mismatch",
495
+ "error",
496
+ f'The row order is inconsistent with declared ordering "{ordering}".',
497
+ )
498
+ return None
499
+
500
+
501
+ def _compare_rows(
502
+ left: list[str],
503
+ right: list[str],
504
+ clauses: list[tuple[int, str]],
505
+ ) -> int:
506
+ for index, direction in clauses:
507
+ left_missing = is_missing(left[index])
508
+ right_missing = is_missing(right[index])
509
+ if left_missing != right_missing:
510
+ return 1 if left_missing else -1
511
+ left_value = _sort_value(left[index])
512
+ right_value = _sort_value(right[index])
513
+ if left_value == right_value:
514
+ continue
515
+ comparison = -1 if left_value < right_value else 1
516
+ return -comparison if direction == "descending" else comparison
517
+ return 0
518
+
519
+
520
+ def _sort_value(value: str) -> tuple[int, Any]:
521
+ if is_missing(value):
522
+ return (3, "")
523
+ text = value.strip()
524
+ if _ISO_DATE_RE.match(text):
525
+ try:
526
+ parsed = datetime.fromisoformat(text)
527
+ return (1, parsed.timestamp())
528
+ except ValueError:
529
+ try:
530
+ return (1, date.fromisoformat(text[:10]).toordinal())
531
+ except ValueError:
532
+ pass
533
+ number = _number(value)
534
+ if number is not None:
535
+ return (0, number)
536
+ return (2, text.casefold())
537
+
538
+
539
+ def _number(value: str) -> float | None:
540
+ match = _NUMBER_RE.match(value)
541
+ if not match:
542
+ return None
543
+ try:
544
+ return float(match.group(0).replace(",", ""))
545
+ except ValueError:
546
+ return None
547
+
548
+
549
+ def _match_header(phrase: str, headers: list[str]) -> int | None:
550
+ target = normalise_label(phrase)
551
+ target_tokens = {
552
+ item
553
+ for item in target.split()
554
+ if item not in {"by", "ordered", "sort", "sorted"}
555
+ }
556
+ best: tuple[int, int] | None = None
557
+ for index, header in enumerate(headers):
558
+ candidate = normalise_label(header)
559
+ candidate_tokens = set(candidate.split())
560
+ overlap = len(target_tokens & candidate_tokens)
561
+ if candidate == target or candidate in target or target in candidate:
562
+ overlap += 10
563
+ if overlap and (best is None or overlap > best[0]):
564
+ best = (overlap, index)
565
+ return None if best is None else best[1]
566
+
567
+
568
+ def _canonical_markdown(
569
+ *,
570
+ headers: list[str],
571
+ rows: list[list[str]],
572
+ alignments: list[str],
573
+ caption: str | None,
574
+ table_id: str,
575
+ ) -> str:
576
+ header_line = "| " + " | ".join(escape_pipe_cell(value) for value in headers) + " |"
577
+ separators = []
578
+ for index in range(len(headers)):
579
+ alignment = alignments[index] if index < len(alignments) else "default"
580
+ separators.append(
581
+ {"left": ":---", "center": ":---:", "right": "---:"}.get(alignment, "---")
582
+ )
583
+ lines = [header_line, "| " + " | ".join(separators) + " |"]
584
+ lines.extend(
585
+ "| " + " | ".join(escape_pipe_cell(value) for value in row) + " |"
586
+ for row in rows
587
+ )
588
+ if caption:
589
+ lines.extend(["", f": {caption} {{#{table_id}}}"])
590
+ return "\n".join(lines)
591
+
592
+
593
+ def _stable_table_id(
594
+ caption: str | None,
595
+ section_path: tuple[str, ...],
596
+ document_path: str,
597
+ headers: list[str],
598
+ ) -> str:
599
+ title = caption or (section_path[-1] if section_path else "table")
600
+ digest = sha256(
601
+ json.dumps(
602
+ {"document": document_path, "section": section_path, "headers": headers},
603
+ ensure_ascii=False,
604
+ sort_keys=True,
605
+ ).encode("utf-8")
606
+ ).hexdigest()[:8]
607
+ return f"{slug(title)}-{digest}"
608
+
609
+
610
+ def _merged_metadata(source: str, supplied: Mapping[str, Any]) -> dict[str, Any]:
611
+ payload: dict[str, Any] = {}
612
+ match = _METADATA_RE.search(source)
613
+ if match:
614
+ try:
615
+ value = json.loads(match.group(1))
616
+ except json.JSONDecodeError as error:
617
+ raise TableNormalisationError(
618
+ f"Invalid table metadata JSON: {error}"
619
+ ) from error
620
+ if not isinstance(value, dict):
621
+ raise TableNormalisationError("Table metadata must be a JSON object")
622
+ payload.update(value)
623
+ payload.update(dict(supplied))
624
+ return payload
625
+
626
+
627
+ def _sentence(value: str) -> str:
628
+ text = collapse_space(value).rstrip()
629
+ if not text:
630
+ return ""
631
+ return text if text.endswith((".", "!", "?")) else text + "."
632
+
633
+
634
+ def _row_id(
635
+ *,
636
+ table_id: str,
637
+ headers: list[str],
638
+ row: list[str],
639
+ row_identity: list[str],
640
+ ) -> str:
641
+ lookup = {normalise_label(header): index for index, header in enumerate(headers)}
642
+ identity_indices = [lookup.get(normalise_label(label)) for label in row_identity]
643
+ if row_identity and all(index is not None for index in identity_indices):
644
+ identity = [
645
+ [headers[int(index)], row[int(index)]]
646
+ for index in identity_indices
647
+ if index is not None
648
+ ]
649
+ payload: dict[str, Any] = {"identity": identity}
650
+ else:
651
+ payload = {"row": list(zip(headers, row, strict=True))}
652
+ digest = sha256(
653
+ json.dumps(payload, ensure_ascii=False, sort_keys=True).encode("utf-8")
654
+ ).hexdigest()[:16]
655
+ return f"{table_id}:row-{digest}"
656
+
657
+
658
+ def _pipe_source_diagnostics(source: str) -> list[TableDiagnostic]:
659
+ """Diagnose ragged ordinary pipe rows before Pandoc fills missing cells."""
660
+
661
+ lines = source.splitlines()
662
+ fence: tuple[str, int] | None = None
663
+ for index in range(len(lines) - 1):
664
+ token = re.match(r"^\s*(`{3,}|~{3,})", lines[index])
665
+ if token:
666
+ marker = token.group(1)[0]
667
+ length = len(token.group(1))
668
+ if fence is None:
669
+ fence = (marker, length)
670
+ elif marker == fence[0] and length >= fence[1]:
671
+ fence = None
672
+ continue
673
+ if fence is not None or not is_pipe_table_start(lines, index):
674
+ continue
675
+
676
+ diagnostics: list[TableDiagnostic] = []
677
+ expected = len(split_pipe_row(lines[index]))
678
+ cursor = index + 2
679
+ row_number = 0
680
+ while cursor < len(lines):
681
+ line = lines[cursor]
682
+ stripped = line.strip()
683
+ if not stripped or stripped.startswith(":") or "|" not in line:
684
+ break
685
+ row_number += 1
686
+ width = len(split_pipe_row(line))
687
+ if width != expected:
688
+ diagnostics.append(
689
+ TableDiagnostic(
690
+ "table.ragged-row",
691
+ "error",
692
+ f"Pipe row has {width} cell(s); the header declares {expected}.",
693
+ row=row_number,
694
+ )
695
+ )
696
+ cursor += 1
697
+ return diagnostics
698
+ return []
699
+
700
+
701
+ def _parse_pipe_fallback(source: str) -> ParsedPandocTable:
702
+ lines = source.splitlines()
703
+ candidates = [
704
+ index for index in range(len(lines)) if is_pipe_table_start(lines, index)
705
+ ]
706
+ if len(candidates) != 1:
707
+ raise TableNormalisationError(
708
+ f"Reduced fallback expects one ordinary pipe table; found {len(candidates)}"
709
+ )
710
+ index = candidates[0]
711
+ headers = split_pipe_row(lines[index], collapse_space)
712
+ alignments = []
713
+ for item in split_pipe_row(lines[index + 1]):
714
+ if item.startswith(":") and item.endswith(":"):
715
+ alignments.append("center")
716
+ elif item.startswith(":"):
717
+ alignments.append("left")
718
+ elif item.endswith(":"):
719
+ alignments.append("right")
720
+ else:
721
+ alignments.append("default")
722
+ rows = []
723
+ cursor = index + 2
724
+ while cursor < len(lines) and "|" in lines[cursor]:
725
+ row = split_pipe_row(lines[cursor], collapse_space)
726
+ if len(row) != len(headers):
727
+ break
728
+ rows.append(row)
729
+ cursor += 1
730
+ caption = None
731
+ table_id = None
732
+ while cursor < len(lines) and not lines[cursor].strip():
733
+ cursor += 1
734
+ if cursor < len(lines) and lines[cursor].lstrip().startswith(":"):
735
+ caption, table_id = strip_caption_id(lines[cursor].lstrip()[1:])
736
+ return ParsedPandocTable(
737
+ table_id=table_id,
738
+ caption=caption,
739
+ headers=headers,
740
+ rows=rows,
741
+ alignments=alignments,
742
+ diagnostics=[],
743
+ attributes={},
744
+ )
745
+
746
+
747
+ def _ordinal_index(headers: list[str]) -> int | None:
748
+ for index, header in enumerate(headers):
749
+ if normalise_label(header) in _ORDINALS:
750
+ return index
751
+ return None
752
+
753
+
754
+ def _string_map(value: Any) -> dict[str, str]:
755
+ if value is None:
756
+ return {}
757
+ if not isinstance(value, Mapping):
758
+ raise TableNormalisationError("labels and units metadata must be mappings")
759
+ return {str(key): str(item) for key, item in value.items()}
760
+
761
+
762
+ def _string_list(value: Any) -> list[str]:
763
+ if value is None:
764
+ return []
765
+ if isinstance(value, str) or not isinstance(value, Iterable):
766
+ raise TableNormalisationError("row_identity metadata must be an array")
767
+ return [str(item) for item in value]
768
+
769
+
770
+ def _optional_text(value: Any) -> str | None:
771
+ if value is None:
772
+ return None
773
+ text = collapse_space(str(value))
774
+ return text or None
775
+
776
+
777
+ def _optional_int(value: Any) -> int | None:
778
+ if value is None:
779
+ return None
780
+ try:
781
+ return int(value)
782
+ except (TypeError, ValueError):
783
+ return None
784
+
785
+
786
+ def _unit_key(value: str) -> str:
787
+ return collapse_space(value).replace(" ", "").casefold()