structa-maestro 0.2.0__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.
Files changed (55) hide show
  1. structa_maestro/__init__.py +294 -0
  2. structa_maestro/batch.py +564 -0
  3. structa_maestro/binding.py +206 -0
  4. structa_maestro/builder/__init__.py +0 -0
  5. structa_maestro/builder/result_builder.py +308 -0
  6. structa_maestro/cli.py +730 -0
  7. structa_maestro/confidence/__init__.py +49 -0
  8. structa_maestro/confidence/calibration.py +990 -0
  9. structa_maestro/confidence/normalizer.py +203 -0
  10. structa_maestro/config.py +111 -0
  11. structa_maestro/contracts/__init__.py +0 -0
  12. structa_maestro/contracts/enums.py +86 -0
  13. structa_maestro/contracts/models.py +229 -0
  14. structa_maestro/contracts/serialization.py +169 -0
  15. structa_maestro/documents/__init__.py +32 -0
  16. structa_maestro/documents/docx_parser.py +215 -0
  17. structa_maestro/documents/eml_parser.py +360 -0
  18. structa_maestro/documents/html_parser.py +337 -0
  19. structa_maestro/documents/inputs.py +277 -0
  20. structa_maestro/documents/loader.py +675 -0
  21. structa_maestro/documents/markdown_parser.py +225 -0
  22. structa_maestro/documents/models.py +33 -0
  23. structa_maestro/documents/normalization.py +24 -0
  24. structa_maestro/documents/pdf_parser.py +186 -0
  25. structa_maestro/documents/txt_parser.py +169 -0
  26. structa_maestro/engine.py +1201 -0
  27. structa_maestro/exceptions.py +38 -0
  28. structa_maestro/provenance/__init__.py +0 -0
  29. structa_maestro/provenance/associator.py +234 -0
  30. structa_maestro/py.typed +0 -0
  31. structa_maestro/review.py +1234 -0
  32. structa_maestro/schema/__init__.py +19 -0
  33. structa_maestro/schema/loader.py +616 -0
  34. structa_maestro/schema/models.py +269 -0
  35. structa_maestro/schema/pydantic_adapter.py +566 -0
  36. structa_maestro/schema/rules.py +526 -0
  37. structa_maestro/schema/serializer.py +156 -0
  38. structa_maestro/strategies/__init__.py +45 -0
  39. structa_maestro/strategies/base.py +101 -0
  40. structa_maestro/strategies/llm_anthropic.py +1142 -0
  41. structa_maestro/strategies/llm_config.py +154 -0
  42. structa_maestro/strategies/llm_gemini.py +1171 -0
  43. structa_maestro/strategies/llm_helpers.py +240 -0
  44. structa_maestro/strategies/llm_openai_compat.py +1183 -0
  45. structa_maestro/strategies/schema_compiler.py +248 -0
  46. structa_maestro/strategies/testing.py +71 -0
  47. structa_maestro/telemetry.py +800 -0
  48. structa_maestro/validation/__init__.py +0 -0
  49. structa_maestro/validation/cross_field.py +463 -0
  50. structa_maestro/validation/validator.py +531 -0
  51. structa_maestro-0.2.0.dist-info/METADATA +394 -0
  52. structa_maestro-0.2.0.dist-info/RECORD +55 -0
  53. structa_maestro-0.2.0.dist-info/WHEEL +4 -0
  54. structa_maestro-0.2.0.dist-info/entry_points.txt +2 -0
  55. structa_maestro-0.2.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,564 @@
1
+ """Stateless, in-process batch document extraction models, scheduler, and directory discovery."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import json
7
+ import os
8
+ import time
9
+ from collections.abc import Callable, Coroutine, Sequence
10
+ from concurrent.futures import FIRST_COMPLETED, Future, ThreadPoolExecutor, wait
11
+ from dataclasses import dataclass
12
+ from pathlib import Path
13
+ from typing import Any
14
+ from uuid import uuid4
15
+
16
+ from structa_maestro.config import DocumentLimits
17
+ from structa_maestro.contracts.enums import (
18
+ IssueSeverity,
19
+ PipelineStage,
20
+ ProcessingStatus,
21
+ ValidationStatus,
22
+ )
23
+ from structa_maestro.contracts.models import (
24
+ DiagnosticIssue,
25
+ ExtractionResult,
26
+ SchemaMetadata,
27
+ SourceMetadata,
28
+ )
29
+ from structa_maestro.documents.inputs import DocumentInput, DocumentInputKind
30
+ from structa_maestro.documents.loader import DocumentLoadResult, read_stream_bounded
31
+ from structa_maestro.exceptions import ConfigurationError
32
+ from structa_maestro.telemetry import BatchProgress
33
+
34
+ MAX_BATCH_WORKERS = 32
35
+ SUPPORTED_BATCH_EXTENSIONS: frozenset[str] = frozenset(
36
+ {".txt", ".pdf", ".docx", ".html", ".htm", ".md", ".markdown", ".eml"}
37
+ )
38
+
39
+
40
+ @dataclass(frozen=True, slots=True)
41
+ class BatchDocumentInput:
42
+ """Immutable per-document batch input pairing a file path with an optional document ID."""
43
+
44
+ path: Path
45
+ document_id: str | None = None
46
+
47
+ def __post_init__(self) -> None:
48
+ raw_path: Any = self.path
49
+ if isinstance(raw_path, str):
50
+ if not raw_path.strip():
51
+ raise ConfigurationError("BatchDocumentInput.path must be a non-empty file path.")
52
+ object.__setattr__(self, "path", Path(raw_path))
53
+ elif isinstance(raw_path, Path):
54
+ if not str(raw_path).strip():
55
+ raise ConfigurationError("BatchDocumentInput.path must be a non-empty file path.")
56
+ else:
57
+ raise ConfigurationError("BatchDocumentInput.path must be a str or pathlib.Path.")
58
+
59
+ if self.document_id is not None:
60
+ if not isinstance(self.document_id, str) or not self.document_id.strip():
61
+ raise ConfigurationError(
62
+ "BatchDocumentInput.document_id must be a non-empty string or None."
63
+ )
64
+ object.__setattr__(self, "document_id", self.document_id.strip())
65
+
66
+
67
+ @dataclass(frozen=True, slots=True)
68
+ class _PreparedBatchItem:
69
+ """Internal normalized batch item holding a DocumentInput and optional pre-captured error."""
70
+
71
+ document_input: DocumentInput
72
+ preloaded_error: DocumentLoadResult | None = None
73
+
74
+
75
+ @dataclass(frozen=True, slots=True)
76
+ class BatchOptions:
77
+ """Immutable in-process batch execution options validated eagerly on construction."""
78
+
79
+ max_workers: int = 1
80
+ fail_fast: bool = False
81
+
82
+ def __post_init__(self) -> None:
83
+ if (
84
+ isinstance(self.max_workers, bool)
85
+ or not isinstance(self.max_workers, int)
86
+ or self.max_workers < 1
87
+ or self.max_workers > MAX_BATCH_WORKERS
88
+ ):
89
+ raise ConfigurationError(
90
+ f"BatchOptions.max_workers must be an integer between 1 and {MAX_BATCH_WORKERS}."
91
+ )
92
+ if not isinstance(self.fail_fast, bool):
93
+ raise ConfigurationError("BatchOptions.fail_fast must be a boolean.")
94
+
95
+
96
+ @dataclass(frozen=True, slots=True)
97
+ class BatchSummary:
98
+ """Immutable aggregate processing and validation statistics for a batch extraction run."""
99
+
100
+ total_documents: int
101
+ processed_documents: int
102
+ skipped_documents: int
103
+ completed_count: int
104
+ partial_count: int
105
+ failed_count: int
106
+ valid_count: int
107
+ invalid_count: int
108
+ not_validated_count: int
109
+ aborted_early: bool
110
+ elapsed_ms: float
111
+
112
+ def to_dict(self) -> dict[str, Any]:
113
+ """Return a JSON-safe dictionary representation of the batch summary."""
114
+ return {
115
+ "total_documents": self.total_documents,
116
+ "processed_documents": self.processed_documents,
117
+ "skipped_documents": self.skipped_documents,
118
+ "completed_count": self.completed_count,
119
+ "partial_count": self.partial_count,
120
+ "failed_count": self.failed_count,
121
+ "valid_count": self.valid_count,
122
+ "invalid_count": self.invalid_count,
123
+ "not_validated_count": self.not_validated_count,
124
+ "aborted_early": self.aborted_early,
125
+ "elapsed_ms": self.elapsed_ms,
126
+ }
127
+
128
+ def to_json(self, *, indent: int | None = None) -> str:
129
+ """Serialize the batch summary to JSON."""
130
+ return json.dumps(self.to_dict(), indent=indent, ensure_ascii=False)
131
+
132
+
133
+ @dataclass(frozen=True, slots=True)
134
+ class BatchExtractionResult:
135
+ """Immutable ordered batch container holding per-document Contract v1.0 results and summary."""
136
+
137
+ batch_id: str
138
+ schema_metadata: SchemaMetadata
139
+ results: tuple[ExtractionResult, ...]
140
+ summary: BatchSummary
141
+
142
+ def to_jsonl(self) -> str:
143
+ """Serialize processed Canonical Output Record Contract v1.0 results as JSON Lines."""
144
+ if not self.results:
145
+ return ""
146
+ return "\n".join(res.to_json(indent=None) for res in self.results) + "\n"
147
+
148
+ def to_dict(self) -> dict[str, Any]:
149
+ """Return a JSON-safe batch envelope preserving Contract v1.0 for every item."""
150
+ return {
151
+ "batch_id": self.batch_id,
152
+ "schema": {
153
+ "schema_id": self.schema_metadata.schema_id,
154
+ "schema_version": self.schema_metadata.schema_version,
155
+ },
156
+ "summary": self.summary.to_dict(),
157
+ "results": [res.to_dict() for res in self.results],
158
+ }
159
+
160
+ def to_json(self, *, indent: int | None = None) -> str:
161
+ """Serialize the batch envelope to JSON."""
162
+ return json.dumps(self.to_dict(), indent=indent, ensure_ascii=False)
163
+
164
+
165
+ def normalize_batch_inputs(
166
+ documents: Sequence[str | Path | BatchDocumentInput | DocumentInput],
167
+ ) -> tuple[DocumentInput, ...]:
168
+ """Eagerly validate and normalize batch input descriptors before opening any file or stream."""
169
+ if isinstance(documents, (str, bytes, bytearray)) or not isinstance(documents, Sequence):
170
+ raise ConfigurationError(
171
+ "Batch documents must be a non-empty sequence of paths, BatchDocumentInput, "
172
+ "or DocumentInput items."
173
+ )
174
+ if len(documents) == 0:
175
+ raise ConfigurationError("Batch documents collection cannot be empty.")
176
+
177
+ normalized: list[DocumentInput] = []
178
+ seen_doc_ids: set[str] = set()
179
+ for idx, item in enumerate(documents):
180
+ if isinstance(item, DocumentInput):
181
+ desc = item
182
+ elif isinstance(item, BatchDocumentInput):
183
+ desc = DocumentInput.from_path(item.path, document_id=item.document_id)
184
+ elif isinstance(item, (str, Path)):
185
+ if isinstance(item, str) and not item.strip():
186
+ raise ConfigurationError(f"Batch document at index {idx} cannot be blank.")
187
+ desc = DocumentInput.from_path(item)
188
+ else:
189
+ raise ConfigurationError(
190
+ f"Batch document at index {idx} must be str, pathlib.Path, "
191
+ "BatchDocumentInput, or DocumentInput."
192
+ )
193
+
194
+ if desc.document_id is not None:
195
+ if desc.document_id in seen_doc_ids:
196
+ raise ConfigurationError(
197
+ f"Duplicate caller-supplied document_id in batch: {desc.document_id!r}"
198
+ )
199
+ seen_doc_ids.add(desc.document_id)
200
+ normalized.append(desc)
201
+
202
+ return tuple(normalized)
203
+
204
+
205
+ def prepare_batch_items(
206
+ inputs: tuple[DocumentInput, ...],
207
+ *,
208
+ limits: DocumentLimits,
209
+ max_workers: int,
210
+ ) -> tuple[_PreparedBatchItem, ...]:
211
+ """Prepare normalized batch items, safely pre-materializing streams for concurrent workers."""
212
+ if max_workers <= 1:
213
+ return tuple(_PreparedBatchItem(document_input=item) for item in inputs)
214
+
215
+ prepared: list[_PreparedBatchItem] = []
216
+ for item in inputs:
217
+ if item.kind != DocumentInputKind.STREAM:
218
+ prepared.append(_PreparedBatchItem(document_input=item))
219
+ continue
220
+
221
+ if item.stream is None:
222
+ raise ConfigurationError("STREAM DocumentInput is missing a binary stream.")
223
+
224
+ raw_bytes, read_err = read_stream_bounded(item.stream, max_bytes=limits.max_file_bytes)
225
+ if read_err is not None or raw_bytes is None:
226
+ doc_id = item.document_id or str(uuid4())
227
+ err_issue = read_err or DiagnosticIssue(
228
+ code="invalid_input",
229
+ severity=IssueSeverity.ERROR,
230
+ stage=PipelineStage.INPUT,
231
+ message="Failed to read input binary stream.",
232
+ )
233
+ failed_load = DocumentLoadResult(
234
+ source=SourceMetadata(
235
+ document_id=doc_id,
236
+ filename=item.filename,
237
+ media_type=None,
238
+ ),
239
+ errors=[err_issue],
240
+ )
241
+ prepared.append(_PreparedBatchItem(document_input=item, preloaded_error=failed_load))
242
+ else:
243
+ snapshot = DocumentInput.from_bytes(
244
+ raw_bytes,
245
+ filename=item.filename,
246
+ document_id=item.document_id,
247
+ media_type=item.media_type,
248
+ )
249
+ prepared.append(_PreparedBatchItem(document_input=snapshot))
250
+
251
+ return tuple(prepared)
252
+
253
+
254
+ def _compute_summary(
255
+ *,
256
+ total_documents: int,
257
+ results: Sequence[ExtractionResult],
258
+ aborted_early: bool,
259
+ elapsed_ms: float,
260
+ ) -> BatchSummary:
261
+ completed = sum(1 for r in results if r.status == ProcessingStatus.COMPLETED)
262
+ partial = sum(1 for r in results if r.status == ProcessingStatus.PARTIAL)
263
+ failed = sum(1 for r in results if r.status == ProcessingStatus.FAILED)
264
+
265
+ valid = sum(1 for r in results if r.validation.status == ValidationStatus.VALID)
266
+ invalid = sum(1 for r in results if r.validation.status == ValidationStatus.INVALID)
267
+ not_validated = sum(1 for r in results if r.validation.status == ValidationStatus.NOT_VALIDATED)
268
+
269
+ processed = len(results)
270
+ return BatchSummary(
271
+ total_documents=total_documents,
272
+ processed_documents=processed,
273
+ skipped_documents=total_documents - processed,
274
+ completed_count=completed,
275
+ partial_count=partial,
276
+ failed_count=failed,
277
+ valid_count=valid,
278
+ invalid_count=invalid,
279
+ not_validated_count=not_validated,
280
+ aborted_early=aborted_early,
281
+ elapsed_ms=round(max(0.0, elapsed_ms), 3),
282
+ )
283
+
284
+
285
+ def run_batch_extraction(
286
+ *,
287
+ inputs: tuple[_PreparedBatchItem, ...],
288
+ schema_metadata: SchemaMetadata,
289
+ options: BatchOptions,
290
+ extract_one: Callable[[_PreparedBatchItem], ExtractionResult],
291
+ batch_id: str | None = None,
292
+ on_item_complete: Callable[[int, ExtractionResult, BatchProgress], None] | None = None,
293
+ ) -> BatchExtractionResult:
294
+ """Execute stateless sequential or bounded concurrent batch extraction in exact input order."""
295
+ started = time.perf_counter()
296
+ resolved_batch_id = batch_id if batch_id is not None else str(uuid4())
297
+ total = len(inputs)
298
+ aborted_early = False
299
+ processed_count = 0
300
+ completed_count = 0
301
+ partial_count = 0
302
+ failed_count = 0
303
+
304
+ def _record_progress(idx: int, res: ExtractionResult, *, aborted_now: bool) -> None:
305
+ nonlocal processed_count, completed_count, partial_count, failed_count
306
+ processed_count += 1
307
+ if res.status == ProcessingStatus.COMPLETED:
308
+ completed_count += 1
309
+ elif res.status == ProcessingStatus.PARTIAL:
310
+ partial_count += 1
311
+ elif res.status == ProcessingStatus.FAILED:
312
+ failed_count += 1
313
+ if on_item_complete is not None:
314
+ on_item_complete(
315
+ idx,
316
+ res,
317
+ BatchProgress(
318
+ batch_id=resolved_batch_id,
319
+ total_documents=total,
320
+ processed_documents=processed_count,
321
+ skipped_documents=0,
322
+ item_index=idx,
323
+ completed_count=completed_count,
324
+ partial_count=partial_count,
325
+ failed_count=failed_count,
326
+ aborted_early=aborted_now,
327
+ ),
328
+ )
329
+
330
+ if options.max_workers == 1:
331
+ ordered_results: list[ExtractionResult] = []
332
+ for idx, doc_input in enumerate(inputs):
333
+ res = extract_one(doc_input)
334
+ ordered_results.append(res)
335
+ will_abort = (
336
+ options.fail_fast and res.status == ProcessingStatus.FAILED and idx < total - 1
337
+ )
338
+ _record_progress(idx, res, aborted_now=will_abort)
339
+ if will_abort:
340
+ aborted_early = True
341
+ break
342
+ final_results = tuple(ordered_results)
343
+ else:
344
+ completed_by_idx: dict[int, ExtractionResult] = {}
345
+ worker_count = min(options.max_workers, total)
346
+ next_idx = 0
347
+ stop_submitting = False
348
+
349
+ with ThreadPoolExecutor(max_workers=worker_count) as pool:
350
+ in_flight: dict[Future[ExtractionResult], int] = {}
351
+
352
+ while next_idx < total and len(in_flight) < worker_count:
353
+ fut = pool.submit(extract_one, inputs[next_idx])
354
+ in_flight[fut] = next_idx
355
+ next_idx += 1
356
+
357
+ while in_flight:
358
+ done, _ = wait(in_flight.keys(), return_when=FIRST_COMPLETED)
359
+ for fut in done:
360
+ idx = in_flight.pop(fut)
361
+ res = fut.result()
362
+ completed_by_idx[idx] = res
363
+ if options.fail_fast and res.status == ProcessingStatus.FAILED:
364
+ stop_submitting = True
365
+ _record_progress(
366
+ idx,
367
+ res,
368
+ aborted_now=stop_submitting and next_idx < total,
369
+ )
370
+
371
+ while not stop_submitting and next_idx < total and len(in_flight) < worker_count:
372
+ fut = pool.submit(extract_one, inputs[next_idx])
373
+ in_flight[fut] = next_idx
374
+ next_idx += 1
375
+
376
+ aborted_early = stop_submitting and len(completed_by_idx) < total
377
+ final_results = tuple(completed_by_idx[i] for i in sorted(completed_by_idx))
378
+
379
+ elapsed_ms = (time.perf_counter() - started) * 1000.0
380
+ summary = _compute_summary(
381
+ total_documents=total,
382
+ results=final_results,
383
+ aborted_early=aborted_early,
384
+ elapsed_ms=elapsed_ms,
385
+ )
386
+ return BatchExtractionResult(
387
+ batch_id=resolved_batch_id,
388
+ schema_metadata=schema_metadata,
389
+ results=final_results,
390
+ summary=summary,
391
+ )
392
+
393
+
394
+ async def run_async_batch_extraction(
395
+ *,
396
+ inputs: tuple[_PreparedBatchItem, ...],
397
+ schema_metadata: SchemaMetadata,
398
+ options: BatchOptions,
399
+ extract_one: Callable[[_PreparedBatchItem], Coroutine[Any, Any, ExtractionResult]],
400
+ batch_id: str | None = None,
401
+ aon_item_complete: (
402
+ Callable[[int, ExtractionResult, BatchProgress], Coroutine[Any, Any, None]] | None
403
+ ) = None,
404
+ ) -> BatchExtractionResult:
405
+ """Execute stateless sequential or bounded concurrent asyncio batch extraction in order."""
406
+ started = time.perf_counter()
407
+ resolved_batch_id = batch_id if batch_id is not None else str(uuid4())
408
+ total = len(inputs)
409
+ aborted_early = False
410
+ processed_count = 0
411
+ completed_count = 0
412
+ partial_count = 0
413
+ failed_count = 0
414
+
415
+ async def _arecord_progress(idx: int, res: ExtractionResult, *, aborted_now: bool) -> None:
416
+ nonlocal processed_count, completed_count, partial_count, failed_count
417
+ processed_count += 1
418
+ if res.status == ProcessingStatus.COMPLETED:
419
+ completed_count += 1
420
+ elif res.status == ProcessingStatus.PARTIAL:
421
+ partial_count += 1
422
+ elif res.status == ProcessingStatus.FAILED:
423
+ failed_count += 1
424
+ if aon_item_complete is not None:
425
+ await aon_item_complete(
426
+ idx,
427
+ res,
428
+ BatchProgress(
429
+ batch_id=resolved_batch_id,
430
+ total_documents=total,
431
+ processed_documents=processed_count,
432
+ skipped_documents=0,
433
+ item_index=idx,
434
+ completed_count=completed_count,
435
+ partial_count=partial_count,
436
+ failed_count=failed_count,
437
+ aborted_early=aborted_now,
438
+ ),
439
+ )
440
+
441
+ if options.max_workers == 1:
442
+ ordered_results: list[ExtractionResult] = []
443
+ for idx, item in enumerate(inputs):
444
+ res = await extract_one(item)
445
+ ordered_results.append(res)
446
+ will_abort = (
447
+ options.fail_fast and res.status == ProcessingStatus.FAILED and idx < total - 1
448
+ )
449
+ await _arecord_progress(idx, res, aborted_now=will_abort)
450
+ if will_abort:
451
+ aborted_early = True
452
+ break
453
+ final_results = tuple(ordered_results)
454
+ else:
455
+ completed_by_idx: dict[int, ExtractionResult] = {}
456
+ worker_count = min(options.max_workers, total)
457
+ next_idx = 0
458
+ stop_submitting = False
459
+ in_flight: dict[asyncio.Task[ExtractionResult], int] = {}
460
+
461
+ try:
462
+ while next_idx < total and len(in_flight) < worker_count:
463
+ task = asyncio.create_task(extract_one(inputs[next_idx]))
464
+ in_flight[task] = next_idx
465
+ next_idx += 1
466
+
467
+ while in_flight:
468
+ done, _ = await asyncio.wait(
469
+ in_flight.keys(),
470
+ return_when=asyncio.FIRST_COMPLETED,
471
+ )
472
+ for task in done:
473
+ idx = in_flight.pop(task)
474
+ res = task.result()
475
+ completed_by_idx[idx] = res
476
+ if options.fail_fast and res.status == ProcessingStatus.FAILED:
477
+ stop_submitting = True
478
+ await _arecord_progress(
479
+ idx,
480
+ res,
481
+ aborted_now=stop_submitting and next_idx < total,
482
+ )
483
+
484
+ while not stop_submitting and next_idx < total and len(in_flight) < worker_count:
485
+ task = asyncio.create_task(extract_one(inputs[next_idx]))
486
+ in_flight[task] = next_idx
487
+ next_idx += 1
488
+ except BaseException:
489
+ # Cancel and cleanly await all active child tasks before propagating CancelledError
490
+ pending_tasks = list(in_flight.keys())
491
+ for task in pending_tasks:
492
+ task.cancel()
493
+ if pending_tasks:
494
+ await asyncio.gather(*pending_tasks, return_exceptions=True)
495
+ raise
496
+
497
+ aborted_early = stop_submitting and len(completed_by_idx) < total
498
+ final_results = tuple(completed_by_idx[i] for i in sorted(completed_by_idx))
499
+
500
+ elapsed_ms = (time.perf_counter() - started) * 1000.0
501
+ summary = _compute_summary(
502
+ total_documents=total,
503
+ results=final_results,
504
+ aborted_early=aborted_early,
505
+ elapsed_ms=elapsed_ms,
506
+ )
507
+ return BatchExtractionResult(
508
+ batch_id=resolved_batch_id,
509
+ schema_metadata=schema_metadata,
510
+ results=final_results,
511
+ summary=summary,
512
+ )
513
+
514
+
515
+ def discover_batch_documents(
516
+ inputs: Sequence[str | Path],
517
+ *,
518
+ recursive: bool = False,
519
+ ) -> list[Path]:
520
+ """Deterministically resolve CLI file and directory inputs without symlink cycles.
521
+
522
+ - Existing directories are scanned lexicographically (non-recursively by default, or
523
+ recursively with ``followlinks=False``), ignoring hidden dotfiles/directories and broken
524
+ symlinks, and keeping files with supported extensions (``.txt``, ``.pdf``, ``.docx``).
525
+ - Explicitly named file paths (including nonexistent paths) are preserved in caller order.
526
+ """
527
+ discovered: list[Path] = []
528
+ for raw in inputs:
529
+ path = Path(raw)
530
+ if path.is_dir():
531
+ dir_files: list[Path] = []
532
+ if recursive:
533
+ for root_str, dirnames, filenames in os.walk(path, followlinks=False):
534
+ # Prune hidden directories & symlinked subdirectories in deterministic order
535
+ root_path = Path(root_str)
536
+ dirnames[:] = sorted(
537
+ d
538
+ for d in dirnames
539
+ if not d.startswith(".") and not (root_path / d).is_symlink()
540
+ )
541
+ for fname in sorted(filenames):
542
+ if fname.startswith("."):
543
+ continue
544
+ candidate = root_path / fname
545
+ if candidate.is_symlink() and not candidate.exists():
546
+ continue
547
+ if (
548
+ candidate.is_file()
549
+ and candidate.suffix.lower() in SUPPORTED_BATCH_EXTENSIONS
550
+ ):
551
+ dir_files.append(candidate)
552
+ else:
553
+ for entry in sorted(path.iterdir(), key=lambda p: p.name):
554
+ if entry.name.startswith("."):
555
+ continue
556
+ if entry.is_symlink() and not entry.exists():
557
+ continue
558
+ if entry.is_file() and entry.suffix.lower() in SUPPORTED_BATCH_EXTENSIONS:
559
+ dir_files.append(entry)
560
+ dir_files.sort(key=lambda p: p.as_posix())
561
+ discovered.extend(dir_files)
562
+ else:
563
+ discovered.append(path)
564
+ return discovered