terraproof 0.8.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 (224) hide show
  1. terraproof/__init__.py +3 -0
  2. terraproof/__main__.py +17 -0
  3. terraproof/_build.py +14 -0
  4. terraproof/_common.py +126 -0
  5. terraproof/_run_helpers.py +216 -0
  6. terraproof/checks/__init__.py +113 -0
  7. terraproof/checks/accuracy.py +421 -0
  8. terraproof/checks/base.py +40 -0
  9. terraproof/checks/crs.py +170 -0
  10. terraproof/checks/geometry.py +98 -0
  11. terraproof/checks/index_formula.py +81 -0
  12. terraproof/checks/processing_full.py +159 -0
  13. terraproof/checks/raster.py +183 -0
  14. terraproof/checks/raster_identity.py +64 -0
  15. terraproof/checks/rs.py +161 -0
  16. terraproof/checks/rs_processing.py +615 -0
  17. terraproof/checks/sar.py +275 -0
  18. terraproof/checks/scope.py +56 -0
  19. terraproof/checks/slope_formula.py +104 -0
  20. terraproof/checks/stac.py +35 -0
  21. terraproof/checks/terrain.py +130 -0
  22. terraproof/cli.py +297 -0
  23. terraproof/data/instructions/engineering.md +14 -0
  24. terraproof/data/instructions/security.md +14 -0
  25. terraproof/data/instructions/simplicity.md +13 -0
  26. terraproof/data/routing/DOMAIN_ROUTING.md +161 -0
  27. terraproof/data/routing/ROUTER_DESIGN.md +173 -0
  28. terraproof/data/routing/SKILL_MANIFEST.md +86 -0
  29. terraproof/data/routing/checks.json +141 -0
  30. terraproof/data/routing/collections.json +47 -0
  31. terraproof/data/routing/registry.json +2212 -0
  32. terraproof/data/routing/rules.json +64 -0
  33. terraproof/data/skills/accuracy-assessment/SKILL.md +213 -0
  34. terraproof/data/skills/accuracy-assessment/UPSTREAM.md +7 -0
  35. terraproof/data/skills/accuracy-assessment/references/stratified-estimator.md +127 -0
  36. terraproof/data/skills/accuracy-assessment/skill.json +103 -0
  37. terraproof/data/skills/brainstorming/SKILL.md +250 -0
  38. terraproof/data/skills/brainstorming/UPSTREAM.md +29 -0
  39. terraproof/data/skills/brainstorming/scripts/frame-template.html +213 -0
  40. terraproof/data/skills/brainstorming/scripts/helper.js +167 -0
  41. terraproof/data/skills/brainstorming/scripts/server.cjs +723 -0
  42. terraproof/data/skills/brainstorming/scripts/start-server.sh +209 -0
  43. terraproof/data/skills/brainstorming/scripts/stop-server.sh +120 -0
  44. terraproof/data/skills/brainstorming/skill.json +73 -0
  45. terraproof/data/skills/brainstorming/spec-document-reviewer-prompt.md +49 -0
  46. terraproof/data/skills/brainstorming/visual-companion.md +299 -0
  47. terraproof/data/skills/crs-and-units/SKILL.md +200 -0
  48. terraproof/data/skills/crs-and-units/UPSTREAM.md +7 -0
  49. terraproof/data/skills/crs-and-units/skill.json +74 -0
  50. terraproof/data/skills/design-postgis-tables/SKILL.md +494 -0
  51. terraproof/data/skills/design-postgis-tables/UPSTREAM.md +21 -0
  52. terraproof/data/skills/design-postgis-tables/skill.json +90 -0
  53. terraproof/data/skills/gdal/SKILL.md +125 -0
  54. terraproof/data/skills/gdal/UPSTREAM.md +22 -0
  55. terraproof/data/skills/gdal/references/gdal-recipes.md +103 -0
  56. terraproof/data/skills/gdal/skill.json +67 -0
  57. terraproof/data/skills/geomaster/README.md +105 -0
  58. terraproof/data/skills/geomaster/SKILL.md +395 -0
  59. terraproof/data/skills/geomaster/UPSTREAM.md +34 -0
  60. terraproof/data/skills/geomaster/references/advanced-gis.md +376 -0
  61. terraproof/data/skills/geomaster/references/big-data.md +363 -0
  62. terraproof/data/skills/geomaster/references/code-examples.md +518 -0
  63. terraproof/data/skills/geomaster/references/coordinate-systems.md +364 -0
  64. terraproof/data/skills/geomaster/references/core-libraries.md +273 -0
  65. terraproof/data/skills/geomaster/references/data-sources.md +330 -0
  66. terraproof/data/skills/geomaster/references/gis-software.md +369 -0
  67. terraproof/data/skills/geomaster/references/industry-applications.md +420 -0
  68. terraproof/data/skills/geomaster/references/machine-learning.md +462 -0
  69. terraproof/data/skills/geomaster/references/programming-languages.md +456 -0
  70. terraproof/data/skills/geomaster/references/remote-sensing.md +370 -0
  71. terraproof/data/skills/geomaster/references/scientific-domains.md +416 -0
  72. terraproof/data/skills/geomaster/references/specialized-topics.md +428 -0
  73. terraproof/data/skills/geomaster/references/troubleshooting.md +439 -0
  74. terraproof/data/skills/geomaster/skill.json +157 -0
  75. terraproof/data/skills/geopandas/SKILL.md +250 -0
  76. terraproof/data/skills/geopandas/UPSTREAM.md +22 -0
  77. terraproof/data/skills/geopandas/references/crs-management.md +231 -0
  78. terraproof/data/skills/geopandas/references/data-io.md +323 -0
  79. terraproof/data/skills/geopandas/references/data-structures.md +207 -0
  80. terraproof/data/skills/geopandas/references/geometric-operations.md +262 -0
  81. terraproof/data/skills/geopandas/references/spatial-analysis.md +294 -0
  82. terraproof/data/skills/geopandas/references/visualization.md +230 -0
  83. terraproof/data/skills/geopandas/scripts/_common.py +605 -0
  84. terraproof/data/skills/geopandas/scripts/crs_reprojection_plan.py +210 -0
  85. terraproof/data/skills/geopandas/scripts/export_plan.py +305 -0
  86. terraproof/data/skills/geopandas/scripts/geometry_validity_report.py +227 -0
  87. terraproof/data/skills/geopandas/scripts/sensitive_coordinates_checklist.py +230 -0
  88. terraproof/data/skills/geopandas/scripts/spatial_join_audit.py +368 -0
  89. terraproof/data/skills/geopandas/scripts/vector_inventory.py +140 -0
  90. terraproof/data/skills/geopandas/skill.json +116 -0
  91. terraproof/data/skills/geoparquet-validation/SKILL.md +125 -0
  92. terraproof/data/skills/geoparquet-validation/UPSTREAM.md +24 -0
  93. terraproof/data/skills/geoparquet-validation/references/distribution-best-practices.md +118 -0
  94. terraproof/data/skills/geoparquet-validation/references/gpio-commands.md +264 -0
  95. terraproof/data/skills/geoparquet-validation/references/tool-comparison.md +155 -0
  96. terraproof/data/skills/geoparquet-validation/skill.json +71 -0
  97. terraproof/data/skills/geospatial-data-discovery/SKILL.md +49 -0
  98. terraproof/data/skills/geospatial-data-discovery/UPSTREAM.md +15 -0
  99. terraproof/data/skills/geospatial-data-discovery/skill.json +51 -0
  100. terraproof/data/skills/geospatial-frontend/SKILL.md +86 -0
  101. terraproof/data/skills/geospatial-frontend/UPSTREAM.md +23 -0
  102. terraproof/data/skills/geospatial-frontend/references/design-system.md +283 -0
  103. terraproof/data/skills/geospatial-frontend/references/user-preferences.md +96 -0
  104. terraproof/data/skills/geospatial-frontend/skill.json +87 -0
  105. terraproof/data/skills/geozarr/SKILL.md +244 -0
  106. terraproof/data/skills/geozarr/UPSTREAM.md +21 -0
  107. terraproof/data/skills/geozarr/skill.json +97 -0
  108. terraproof/data/skills/networkx/SKILL.md +440 -0
  109. terraproof/data/skills/networkx/UPSTREAM.md +22 -0
  110. terraproof/data/skills/networkx/references/algorithms.md +384 -0
  111. terraproof/data/skills/networkx/references/generators.md +385 -0
  112. terraproof/data/skills/networkx/references/graph-basics.md +284 -0
  113. terraproof/data/skills/networkx/references/io.md +457 -0
  114. terraproof/data/skills/networkx/references/visualization.md +531 -0
  115. terraproof/data/skills/networkx/skill.json +93 -0
  116. terraproof/data/skills/raster-processing/SKILL.md +222 -0
  117. terraproof/data/skills/raster-processing/UPSTREAM.md +7 -0
  118. terraproof/data/skills/raster-processing/skill.json +81 -0
  119. terraproof/data/skills/sar-basics/SKILL.md +202 -0
  120. terraproof/data/skills/sar-basics/UPSTREAM.md +7 -0
  121. terraproof/data/skills/sar-basics/references/calibration-lut.md +98 -0
  122. terraproof/data/skills/sar-basics/skill.json +97 -0
  123. terraproof/data/skills/satellite-preprocessing/SKILL.md +241 -0
  124. terraproof/data/skills/satellite-preprocessing/UPSTREAM.md +7 -0
  125. terraproof/data/skills/satellite-preprocessing/skill.json +84 -0
  126. terraproof/data/skills/scientific-visualization/SKILL.md +285 -0
  127. terraproof/data/skills/scientific-visualization/UPSTREAM.md +25 -0
  128. terraproof/data/skills/scientific-visualization/assets/color_palettes.py +263 -0
  129. terraproof/data/skills/scientific-visualization/assets/nature.mplstyle +68 -0
  130. terraproof/data/skills/scientific-visualization/assets/presentation.mplstyle +68 -0
  131. terraproof/data/skills/scientific-visualization/assets/publication.mplstyle +77 -0
  132. terraproof/data/skills/scientific-visualization/assets/publisher_profiles.json +269 -0
  133. terraproof/data/skills/scientific-visualization/references/color_palettes.md +227 -0
  134. terraproof/data/skills/scientific-visualization/references/journal_requirements.md +169 -0
  135. terraproof/data/skills/scientific-visualization/references/matplotlib_examples.md +336 -0
  136. terraproof/data/skills/scientific-visualization/references/publication_guidelines.md +196 -0
  137. terraproof/data/skills/scientific-visualization/references/sources.md +76 -0
  138. terraproof/data/skills/scientific-visualization/scripts/_common.py +136 -0
  139. terraproof/data/skills/scientific-visualization/scripts/export_plan.py +493 -0
  140. terraproof/data/skills/scientific-visualization/scripts/figure_export.py +642 -0
  141. terraproof/data/skills/scientific-visualization/scripts/image_metadata.py +731 -0
  142. terraproof/data/skills/scientific-visualization/scripts/palette_audit.py +327 -0
  143. terraproof/data/skills/scientific-visualization/scripts/style_presets.py +501 -0
  144. terraproof/data/skills/scientific-visualization/scripts/style_preview.py +232 -0
  145. terraproof/data/skills/scientific-visualization/skill.json +95 -0
  146. terraproof/data/skills/spectral-indices/SKILL.md +235 -0
  147. terraproof/data/skills/spectral-indices/UPSTREAM.md +7 -0
  148. terraproof/data/skills/spectral-indices/skill.json +88 -0
  149. terraproof/data/skills/stac-and-cloud-access/SKILL.md +209 -0
  150. terraproof/data/skills/stac-and-cloud-access/UPSTREAM.md +7 -0
  151. terraproof/data/skills/stac-and-cloud-access/references/run-manifest.md +94 -0
  152. terraproof/data/skills/stac-and-cloud-access/skill.json +98 -0
  153. terraproof/data/skills/statistical-analysis/SKILL.md +446 -0
  154. terraproof/data/skills/statistical-analysis/UPSTREAM.md +24 -0
  155. terraproof/data/skills/statistical-analysis/references/assumptions_and_diagnostics.md +379 -0
  156. terraproof/data/skills/statistical-analysis/references/bayesian_statistics.md +686 -0
  157. terraproof/data/skills/statistical-analysis/references/effect_sizes_and_power.md +649 -0
  158. terraproof/data/skills/statistical-analysis/references/reporting_standards.md +482 -0
  159. terraproof/data/skills/statistical-analysis/references/test_selection_guide.md +129 -0
  160. terraproof/data/skills/statistical-analysis/scripts/assumption_checks.py +652 -0
  161. terraproof/data/skills/statistical-analysis/skill.json +127 -0
  162. terraproof/data/skills/systematic-debugging/SKILL.md +283 -0
  163. terraproof/data/skills/systematic-debugging/UPSTREAM.md +28 -0
  164. terraproof/data/skills/systematic-debugging/condition-based-waiting-example.ts +158 -0
  165. terraproof/data/skills/systematic-debugging/condition-based-waiting.md +115 -0
  166. terraproof/data/skills/systematic-debugging/defense-in-depth.md +122 -0
  167. terraproof/data/skills/systematic-debugging/find-polluter.sh +72 -0
  168. terraproof/data/skills/systematic-debugging/root-cause-tracing.md +169 -0
  169. terraproof/data/skills/systematic-debugging/skill.json +88 -0
  170. terraproof/data/skills/time-series-and-change/SKILL.md +217 -0
  171. terraproof/data/skills/time-series-and-change/UPSTREAM.md +7 -0
  172. terraproof/data/skills/time-series-and-change/references/change-methods.md +42 -0
  173. terraproof/data/skills/time-series-and-change/skill.json +116 -0
  174. terraproof/data/skills/vector-quality/SKILL.md +204 -0
  175. terraproof/data/skills/vector-quality/UPSTREAM.md +7 -0
  176. terraproof/data/skills/vector-quality/skill.json +82 -0
  177. terraproof/data/skills/verification/SKILL.md +120 -0
  178. terraproof/data/skills/verification/UPSTREAM.md +31 -0
  179. terraproof/data/skills/verification/skill.json +67 -0
  180. terraproof/data/skills/writing-plans/SKILL.md +171 -0
  181. terraproof/data/skills/writing-plans/UPSTREAM.md +23 -0
  182. terraproof/data/skills/writing-plans/plan-document-reviewer-prompt.md +49 -0
  183. terraproof/data/skills/writing-plans/skill.json +80 -0
  184. terraproof/data/sources/SOURCES.md +392 -0
  185. terraproof/data/third_party/isaaccorley-geospatial-skills/LICENSE +176 -0
  186. terraproof/data/third_party/isaaccorley-geospatial-skills/NOTICE.md +17 -0
  187. terraproof/data/third_party/kdense-scientific-agent-skills/LICENSE +21 -0
  188. terraproof/data/third_party/kdense-scientific-agent-skills/NOTICE.md +19 -0
  189. terraproof/data/third_party/superpowers/LICENSE +21 -0
  190. terraproof/data/third_party/superpowers/NOTICE.md +17 -0
  191. terraproof/data/third_party/timescale-pg-aiguide/LICENSE +176 -0
  192. terraproof/data/third_party/timescale-pg-aiguide/NOTICE.md +14 -0
  193. terraproof/evidence/__init__.py +16 -0
  194. terraproof/evidence/grade.py +24 -0
  195. terraproof/evidence/report.py +211 -0
  196. terraproof/inspect/__init__.py +41 -0
  197. terraproof/inspect/raster.py +104 -0
  198. terraproof/inspect/stac.py +45 -0
  199. terraproof/inspect/vector.py +115 -0
  200. terraproof/install/__init__.py +174 -0
  201. terraproof/install/__main__.py +8 -0
  202. terraproof/install/agents.py +398 -0
  203. terraproof/mcp/__init__.py +5 -0
  204. terraproof/mcp/__main__.py +18 -0
  205. terraproof/mcp/server.py +352 -0
  206. terraproof/mcp/skills.py +128 -0
  207. terraproof/preflight.py +1121 -0
  208. terraproof/provenance/__init__.py +7 -0
  209. terraproof/provenance/__main__.py +114 -0
  210. terraproof/provenance/_core.py +432 -0
  211. terraproof/router/__init__.py +376 -0
  212. terraproof/router/__main__.py +33 -0
  213. terraproof/router/evaluate.py +115 -0
  214. terraproof/router/index.py +123 -0
  215. terraproof/router/intent.py +84 -0
  216. terraproof/router/lexicon.py +416 -0
  217. terraproof/router/semantic.py +157 -0
  218. terraproof/router/signals.py +531 -0
  219. terraproof/router/text.py +137 -0
  220. terraproof-0.8.0.dist-info/METADATA +219 -0
  221. terraproof-0.8.0.dist-info/RECORD +224 -0
  222. terraproof-0.8.0.dist-info/WHEEL +5 -0
  223. terraproof-0.8.0.dist-info/licenses/LICENSE +21 -0
  224. terraproof-0.8.0.dist-info/top_level.txt +1 -0
terraproof/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """Terraproof: inspect geospatial datasets, run deterministic checks, and grade the evidence."""
2
+
3
+ __version__ = "0.8.0"
terraproof/__main__.py ADDED
@@ -0,0 +1,17 @@
1
+ """Entry point for `python -m terraproof`."""
2
+
3
+ import sys
4
+
5
+ from terraproof.cli import main
6
+
7
+
8
+ def _run() -> None:
9
+ for stream in (sys.stdout, sys.stderr):
10
+ reconfigure = getattr(stream, "reconfigure", None)
11
+ if reconfigure is not None:
12
+ reconfigure(encoding="utf-8")
13
+ sys.exit(main())
14
+
15
+
16
+ if __name__ == "__main__":
17
+ _run()
terraproof/_build.py ADDED
@@ -0,0 +1,14 @@
1
+ """Include the existing runtime assets in wheels without moving source files."""
2
+
3
+ from pathlib import Path
4
+
5
+ from setuptools.command.build_py import build_py
6
+
7
+
8
+ class BuildPy(build_py):
9
+ def run(self):
10
+ super().run()
11
+ root = Path(__file__).resolve().parents[2]
12
+ destination = Path(self.build_lib) / 'terraproof' / 'data'
13
+ for relative in ('skills', 'routing', 'instructions', 'sources', 'third_party'):
14
+ self.copy_tree(str(root / relative), str(destination / relative))
terraproof/_common.py ADDED
@@ -0,0 +1,126 @@
1
+ """Helpers shared by the inspectors, checks, and evidence report."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import math
7
+ import os
8
+ import sys
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ import numpy as np
13
+ import pyproj
14
+
15
+ GEOMETRY_TYPE_NAMES = {
16
+ 0: "Point",
17
+ 1: "LineString",
18
+ 2: "LinearRing",
19
+ 3: "Polygon",
20
+ 4: "MultiPoint",
21
+ 5: "MultiLineString",
22
+ 6: "MultiPolygon",
23
+ 7: "GeometryCollection",
24
+ }
25
+
26
+
27
+ class InputError(ValueError):
28
+ """An input file is missing, unreadable, or not a supported dataset."""
29
+
30
+
31
+ def assets_root() -> Path:
32
+ """The directory that holds `skills/` and `routing/`, in a checkout or an install.
33
+
34
+ The current working directory is never used: the assets belong to the installed
35
+ package, not to whichever project happens to be open.
36
+ """
37
+ package = Path(__file__).resolve().parent
38
+ candidates = [package, package / "data", package / "_data", package / "resources",
39
+ Path(sys.prefix) / "share" / "terraproof", *package.parents]
40
+ for candidate in candidates:
41
+ if (candidate / "routing" / "registry.json").is_file() and (candidate / "skills").is_dir():
42
+ return candidate
43
+ raise InputError("Terraproof skills/routing assets not found beside the package or in share/terraproof")
44
+
45
+
46
+ def sha256_and_size(path: str | os.PathLike) -> tuple[str, int]:
47
+ """Return the SHA-256 hex digest and byte size of a file."""
48
+ digest = hashlib.sha256()
49
+ size = 0
50
+ with open(path, "rb") as handle:
51
+ for chunk in iter(lambda: handle.read(1 << 20), b""):
52
+ digest.update(chunk)
53
+ size += len(chunk)
54
+ return digest.hexdigest(), size
55
+
56
+
57
+ def _horizontal_component(crs: pyproj.CRS) -> pyproj.CRS | None:
58
+ """The horizontal part of a compound CRS (its first non-vertical component), or the CRS itself."""
59
+ if not crs.is_compound:
60
+ return crs
61
+ for component in crs.sub_crs_list:
62
+ if not component.is_vertical:
63
+ return component
64
+ return None
65
+
66
+
67
+ def _kind(crs: pyproj.CRS | None) -> str:
68
+ if crs is None:
69
+ return "none"
70
+ if crs.is_projected:
71
+ return "projected"
72
+ if crs.is_geographic:
73
+ return "geographic"
74
+ if crs.is_geocentric:
75
+ return "geocentric"
76
+ return "other"
77
+
78
+
79
+ def crs_summary(crs_value: Any) -> dict | None:
80
+ """Describe a CRS given as WKT, an authority string, or a rasterio/pyproj CRS.
81
+
82
+ `horizontal_kind` and `horizontal_axis_units` describe the horizontal component, which
83
+ for a compound CRS (horizontal + vertical) is the first non-vertical sub-CRS. `horizontal_kind`
84
+ is one of projected, geographic, geocentric, other, or none. Returns None when there is no CRS.
85
+ """
86
+ if crs_value is None:
87
+ return None
88
+ crs = pyproj.CRS.from_user_input(crs_value)
89
+ axis_units = crs.axis_info[0].unit_name if crs.axis_info else None
90
+ horizontal = _horizontal_component(crs)
91
+ horizontal_units = horizontal.axis_info[0].unit_name if horizontal is not None and horizontal.axis_info else None
92
+ return {
93
+ "wkt": crs.to_wkt(),
94
+ "epsg": crs.to_epsg(),
95
+ "name": crs.name,
96
+ "is_geographic": bool(crs.is_geographic),
97
+ "is_projected": bool(crs.is_projected),
98
+ "is_geocentric": bool(crs.is_geocentric),
99
+ "axis_units": axis_units,
100
+ "horizontal_kind": _kind(horizontal),
101
+ "horizontal_axis_units": horizontal_units,
102
+ }
103
+
104
+
105
+ def jsonable(value: Any) -> Any:
106
+ """Convert numpy and path values to JSON-safe Python values.
107
+
108
+ Non-finite floats become the strings "NaN", "Infinity", and "-Infinity" so
109
+ that a NaN nodata value is not mistaken for "no nodata declared".
110
+ """
111
+ if isinstance(value, dict):
112
+ return {str(key): jsonable(item) for key, item in value.items()}
113
+ if isinstance(value, (list, tuple)):
114
+ return [jsonable(item) for item in value]
115
+ if isinstance(value, np.ndarray):
116
+ return [jsonable(item) for item in value.tolist()]
117
+ if isinstance(value, np.generic):
118
+ value = value.item()
119
+ if isinstance(value, os.PathLike):
120
+ return os.fspath(value)
121
+ if isinstance(value, float):
122
+ if math.isnan(value):
123
+ return "NaN"
124
+ if math.isinf(value):
125
+ return "Infinity" if value > 0 else "-Infinity"
126
+ return value
@@ -0,0 +1,216 @@
1
+ """Shared helpers used by both the CLI and the MCP server for run inputs.
2
+
3
+ This keeps sample/area loading and manifest-coverage logic identical across the
4
+ two entry points.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import os
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ from terraproof._common import InputError
15
+ from terraproof.checks.accuracy import read_samples as _read_csv_samples
16
+ from terraproof.checks.base import result
17
+ from terraproof.provenance import verify_manifest as _verify_manifest
18
+ from terraproof.provenance._core import _is_within_root, _resolve_recorded_path, _workspace_for
19
+
20
+
21
+ def _normalise_sample_record(raw: Any) -> dict:
22
+ """Return a {map_class, ref_class, stratum_weight} dict, rejecting malformed records."""
23
+ if isinstance(raw, dict):
24
+ map_value = raw.get("map_class")
25
+ ref_value = raw.get("ref_class")
26
+ map_class = "" if map_value is None else str(map_value).strip()
27
+ ref_class = "" if ref_value is None else str(ref_value).strip()
28
+ weight = raw.get("stratum_weight")
29
+ elif isinstance(raw, (list, tuple)):
30
+ if len(raw) < 2:
31
+ raise InputError(f"sample record must have at least map_class and ref_class: {raw!r}")
32
+ map_class = str(raw[0]).strip()
33
+ ref_class = str(raw[1]).strip()
34
+ weight = raw[2] if len(raw) > 2 else None
35
+ else:
36
+ raise InputError(f"sample record must be a dict or sequence: {raw!r}")
37
+
38
+ if not map_class or not ref_class:
39
+ raise InputError(f"sample record missing map_class or ref_class: {raw!r}")
40
+
41
+ if weight is not None:
42
+ try:
43
+ weight = float(weight)
44
+ except (TypeError, ValueError) as exc:
45
+ raise InputError(f"stratum_weight must be a number: {weight!r}") from exc
46
+
47
+ return {"map_class": map_class, "ref_class": ref_class, "stratum_weight": weight}
48
+
49
+
50
+ def load_accuracy_samples(value: Any) -> dict:
51
+ """Load reference samples from a CSV/JSON file, a list, or a records dict.
52
+
53
+ The returned dict matches ``terraproof.checks.accuracy.read_samples``:
54
+ ``{"path", "records": [{map_class, ref_class, stratum_weight}, ...], "has_weights"}``.
55
+ """
56
+ if isinstance(value, dict):
57
+ if "records" not in value:
58
+ raise InputError("accuracy_samples dict must contain a 'records' list")
59
+ records = [_normalise_sample_record(r) for r in value["records"]]
60
+ has_weights = bool(
61
+ value.get("has_weights", any(r["stratum_weight"] is not None for r in records))
62
+ )
63
+ return {"path": value.get("path", "(supplied dict)"), "records": records, "has_weights": has_weights}
64
+
65
+ if isinstance(value, list):
66
+ records = [_normalise_sample_record(r) for r in value]
67
+ return {
68
+ "path": "(supplied list)",
69
+ "records": records,
70
+ "has_weights": any(r["stratum_weight"] is not None for r in records),
71
+ }
72
+
73
+ if isinstance(value, str):
74
+ path = Path(value)
75
+ if not path.is_file():
76
+ raise InputError(f"accuracy samples file not found: {value}")
77
+ if path.suffix.lower() == ".csv":
78
+ return _read_csv_samples(path)
79
+ with open(path, encoding="utf-8") as handle:
80
+ data = json.load(handle)
81
+ if isinstance(data, dict) and "records" in data:
82
+ records = [_normalise_sample_record(r) for r in data["records"]]
83
+ has_weights = bool(
84
+ data.get("has_weights", any(r["stratum_weight"] is not None for r in records))
85
+ )
86
+ return {"path": str(path), "records": records, "has_weights": has_weights}
87
+ if isinstance(data, list):
88
+ records = [_normalise_sample_record(r) for r in data]
89
+ return {
90
+ "path": str(path),
91
+ "records": records,
92
+ "has_weights": any(r["stratum_weight"] is not None for r in records),
93
+ }
94
+ raise InputError(f"accuracy samples JSON must be a list or {{records: [...]}}: {value}")
95
+
96
+ raise InputError("accuracy_samples must be a file path, dict, or list")
97
+
98
+
99
+ def load_class_areas(value: Any) -> dict:
100
+ """Load a class-name-to-area mapping from a dict or a JSON file."""
101
+ if isinstance(value, dict):
102
+ return value
103
+ if isinstance(value, str):
104
+ path = Path(value)
105
+ if not path.is_file():
106
+ raise InputError(f"class areas file not found: {value}")
107
+ with open(path, encoding="utf-8") as handle:
108
+ data = json.load(handle)
109
+ if not isinstance(data, dict):
110
+ raise InputError(f"class areas JSON must be an object: {value}")
111
+ return data
112
+ raise InputError("class_areas must be a dict or file path")
113
+
114
+
115
+ def verify_manifest_coverage(
116
+ manifest_path: str | os.PathLike,
117
+ checked_paths: list[str],
118
+ root: str | os.PathLike | None = None,
119
+ ) -> Any:
120
+ """Verify a manifest and confirm it covers every path in ``checked_paths``.
121
+
122
+ ``checked_paths`` should include all files that contribute to the check run
123
+ (primary inputs, compare-to, reference-input, QA, accuracy samples, class
124
+ areas). The manifest's own ``root_rule`` is respected when resolving recorded
125
+ paths. A malformed manifest returns a ``provenance.reproducible`` failure
126
+ rather than raising.
127
+ """
128
+ manifest_path_obj = Path(manifest_path).resolve()
129
+ try:
130
+ with open(manifest_path_obj, encoding="utf-8") as handle:
131
+ manifest = json.load(handle)
132
+ except (OSError, json.JSONDecodeError) as exc:
133
+ return result(
134
+ "provenance.reproducible",
135
+ "fail",
136
+ f"cannot read manifest: {exc}",
137
+ manifest=str(manifest_path_obj),
138
+ )
139
+
140
+ if not isinstance(manifest, dict):
141
+ return result(
142
+ "provenance.reproducible",
143
+ "fail",
144
+ "manifest must be a JSON object",
145
+ manifest=str(manifest_path_obj),
146
+ )
147
+
148
+ schema = manifest.get("schema")
149
+ if schema != "terraproof.manifest/0.1":
150
+ return result(
151
+ "provenance.reproducible",
152
+ "fail",
153
+ f"unsupported manifest schema: {schema!r}",
154
+ manifest=str(manifest_path_obj),
155
+ schema=schema,
156
+ )
157
+
158
+ core = manifest.get("core", {})
159
+
160
+ # Let the provenance verifier handle hash, missing/changed files, and version drift.
161
+ # Its schema/structure errors are part of the provenance result, not an API crash.
162
+ try:
163
+ provenance_result = _verify_manifest(manifest_path_obj, root=root)
164
+ except Exception as exc: # malformed schema/structure must preserve CLI/MCP parity
165
+ return result(
166
+ "provenance.reproducible",
167
+ "fail",
168
+ f"invalid manifest structure: {exc}",
169
+ manifest=str(manifest_path_obj),
170
+ )
171
+ if provenance_result.status == "fail":
172
+ return provenance_result
173
+
174
+ root_path = Path(root).resolve() if root else manifest_path_obj.parent
175
+ root_rule = core.get("root_rule", "manifest-parent" if root is None else "explicit")
176
+ workspace = _workspace_for(root_path, root_rule)
177
+
178
+ recorded: set[str] = set()
179
+ for record in core.get("files", []):
180
+ try:
181
+ resolved = _resolve_recorded_path(record["path"], root_path)
182
+ except Exception as exc:
183
+ return result(
184
+ "provenance.reproducible",
185
+ "fail",
186
+ f"invalid recorded path {record.get('path')!r}: {exc}",
187
+ manifest=str(manifest_path_obj),
188
+ )
189
+ if not _is_within_root(resolved, workspace):
190
+ return result(
191
+ "provenance.reproducible",
192
+ "fail",
193
+ f"recorded path escapes workspace: {record.get('path')}",
194
+ manifest=str(manifest_path_obj),
195
+ workspace=str(workspace),
196
+ )
197
+ recorded.add(str(resolved))
198
+
199
+ missing: list[str] = []
200
+ for path in checked_paths:
201
+ if path is None or not isinstance(path, (str, os.PathLike)) or not str(path):
202
+ continue
203
+ resolved = str(Path(path).resolve())
204
+ if resolved not in recorded:
205
+ missing.append(str(path))
206
+
207
+ if missing:
208
+ return result(
209
+ "provenance.reproducible",
210
+ "fail",
211
+ f"manifest does not cover the checked path(s): {', '.join(missing)}",
212
+ manifest=str(manifest_path_obj),
213
+ uncovered_paths=missing,
214
+ )
215
+
216
+ return provenance_result
@@ -0,0 +1,113 @@
1
+ """Deterministic checks. Checks that do not apply to an input are omitted; checks that apply but cannot run are not-run."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from terraproof.checks import accuracy, crs, geometry, raster, rs, rs_processing, sar, scope, stac, terrain
6
+ from terraproof.checks import index_formula as index_checks
7
+ from terraproof.checks import slope_formula as slope_checks, raster_identity as identity_checks
8
+ from terraproof.checks.base import STATUSES, CheckResult, result
9
+
10
+ __all__ = ["STATUSES", "CheckResult", "result", "run_checks"]
11
+
12
+
13
+ def run_checks(
14
+ inputs: list[dict],
15
+ *,
16
+ compare_to: dict | None = None,
17
+ operation: str | None = None,
18
+ resampling: str | None = None,
19
+ categorical: bool = False,
20
+ expect: str | None = None,
21
+ reference_input: dict | None = None,
22
+ encoding: str | None = None,
23
+ qa_path: str | None = None,
24
+ qa_kind: str | None = None,
25
+ time_range: tuple[str, str] | list | None = None,
26
+ sar_expect: str | None = None,
27
+ accuracy_samples: dict | None = None,
28
+ class_areas=None,
29
+ min_per_class: int | None = None,
30
+ estimates_requested: bool = False,
31
+ dem: dict | None = None,
32
+ slope_method: str | None = None,
33
+ raster_identity: bool = False,
34
+ index_formula: str | None = None,
35
+ nir: dict | None = None,
36
+ red: dict | None = None,
37
+ processing_full_scan: bool = False,
38
+ ) -> list[CheckResult]:
39
+ """Run every check that applies to the inspected inputs, in a fixed order."""
40
+ vectors = [d for d in inputs if d["kind"] == "vector"]
41
+ rasters = [d for d in inputs if d["kind"] == "raster"]
42
+ stac_items = [d for d in inputs if d["kind"] == "stac"]
43
+ georeferenced = [d for d in inputs if d["kind"] in ("vector", "raster")]
44
+
45
+ results: list[CheckResult] = []
46
+ results += crs.check_defined(georeferenced)
47
+ if len(georeferenced) >= 2:
48
+ results += crs.check_consistent(georeferenced)
49
+ if operation:
50
+ results += crs.check_metric_operation(georeferenced, operation)
51
+
52
+ for dataset in vectors:
53
+ results += geometry.check_geometry(dataset)
54
+ if compare_to is not None and (vectors or not raster_identity):
55
+ results += scope.check_record_count(vectors, compare_to)
56
+
57
+ for dataset in rasters:
58
+ results += raster.check_nodata(dataset)
59
+ results += raster.check_cog_layout(dataset)
60
+ if len(rasters) >= 2:
61
+ results += raster.check_grid_alignment(rasters)
62
+ if resampling is not None and categorical:
63
+ results += raster.check_resampling(rasters, resampling)
64
+
65
+ if expect == "reflectance":
66
+ results += rs.check_reflectance(rasters)
67
+ elif expect == "index":
68
+ results += rs.check_index(rasters)
69
+
70
+ for dataset in stac_items:
71
+ results += stac.check_provenance(dataset)
72
+
73
+ # Processing-level checks (§3.3). Each one is emitted only when its own input was supplied:
74
+ # a check that applies but cannot run reports not-run itself rather than being omitted.
75
+ if reference_input is not None or encoding is not None:
76
+ for dataset in rasters:
77
+ results += rs_processing.check_scale_applied_once(dataset, reference_input, encoding,
78
+ full_scan=processing_full_scan)
79
+ if qa_path is not None or qa_kind is not None:
80
+ for dataset in rasters:
81
+ results += rs_processing.check_cloud_mask_applied(dataset, qa_path, qa_kind, full_scan=processing_full_scan)
82
+ if time_range is not None:
83
+ results += rs_processing.check_temporal_scope(stac_items, time_range)
84
+
85
+ if index_formula is not None or nir is not None or red is not None:
86
+ for dataset in inputs:
87
+ results += index_checks.check_index_formula(dataset, index_formula, nir, red)
88
+
89
+ if slope_method is not None:
90
+ for dataset in inputs:
91
+ results += slope_checks.check_slope_formula(dataset, dem, slope_method)
92
+ elif dem is not None:
93
+ for dataset in rasters:
94
+ results += terrain.check_slope_consistent(dataset, dem)
95
+
96
+ if raster_identity:
97
+ for dataset in inputs:
98
+ results += identity_checks.check_source_identity(dataset, compare_to)
99
+
100
+ if sar_expect is not None:
101
+ results += sar.check_value_domain(rasters, sar_expect)
102
+ results += sar.check_geocoded(rasters)
103
+
104
+ if accuracy_samples is not None:
105
+ design_kwargs = {} if min_per_class is None else {"min_per_class": min_per_class}
106
+ results += accuracy.check_sample_design(
107
+ accuracy_samples,
108
+ class_areas=class_areas,
109
+ estimates_requested=estimates_requested,
110
+ **design_kwargs,
111
+ )
112
+ results += accuracy.check_estimates(accuracy_samples, class_areas=class_areas)
113
+ return results