terraproof 0.0.0-stage → 0.4.0

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 (182) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +356 -2
  3. package/bin/terraproof.js +4 -0
  4. package/dist/router/apply.js +147 -0
  5. package/dist/router/classify.js +111 -0
  6. package/dist/router/explain.js +9 -0
  7. package/dist/router/index.js +272 -0
  8. package/dist/router/resolve.js +239 -0
  9. package/dist/router/score.js +60 -0
  10. package/dist/router/types.js +1 -0
  11. package/dist/router/validate.js +81 -0
  12. package/instructions/engineering.md +14 -0
  13. package/instructions/security.md +14 -0
  14. package/instructions/simplicity.md +13 -0
  15. package/package.json +65 -4
  16. package/routing/DOMAIN_ROUTING.md +161 -0
  17. package/routing/ROUTER_DESIGN.md +173 -0
  18. package/routing/SKILL_MANIFEST.md +86 -0
  19. package/routing/checks.json +121 -0
  20. package/routing/collections.json +47 -0
  21. package/routing/registry.json +2211 -0
  22. package/routing/rules.json +64 -0
  23. package/skills/accuracy-assessment/SKILL.md +213 -0
  24. package/skills/accuracy-assessment/UPSTREAM.md +7 -0
  25. package/skills/accuracy-assessment/references/stratified-estimator.md +127 -0
  26. package/skills/accuracy-assessment/skill.json +103 -0
  27. package/skills/brainstorming/SKILL.md +250 -0
  28. package/skills/brainstorming/UPSTREAM.md +29 -0
  29. package/skills/brainstorming/scripts/frame-template.html +213 -0
  30. package/skills/brainstorming/scripts/helper.js +167 -0
  31. package/skills/brainstorming/scripts/server.cjs +723 -0
  32. package/skills/brainstorming/scripts/start-server.sh +209 -0
  33. package/skills/brainstorming/scripts/stop-server.sh +120 -0
  34. package/skills/brainstorming/skill.json +73 -0
  35. package/skills/brainstorming/spec-document-reviewer-prompt.md +49 -0
  36. package/skills/brainstorming/visual-companion.md +299 -0
  37. package/skills/crs-and-units/SKILL.md +200 -0
  38. package/skills/crs-and-units/UPSTREAM.md +7 -0
  39. package/skills/crs-and-units/skill.json +74 -0
  40. package/skills/design-postgis-tables/SKILL.md +494 -0
  41. package/skills/design-postgis-tables/UPSTREAM.md +21 -0
  42. package/skills/design-postgis-tables/skill.json +90 -0
  43. package/skills/gdal/SKILL.md +125 -0
  44. package/skills/gdal/UPSTREAM.md +22 -0
  45. package/skills/gdal/references/gdal-recipes.md +103 -0
  46. package/skills/gdal/skill.json +66 -0
  47. package/skills/geomaster/README.md +105 -0
  48. package/skills/geomaster/SKILL.md +366 -0
  49. package/skills/geomaster/UPSTREAM.md +21 -0
  50. package/skills/geomaster/references/advanced-gis.md +376 -0
  51. package/skills/geomaster/references/big-data.md +363 -0
  52. package/skills/geomaster/references/code-examples.md +531 -0
  53. package/skills/geomaster/references/coordinate-systems.md +364 -0
  54. package/skills/geomaster/references/core-libraries.md +273 -0
  55. package/skills/geomaster/references/data-sources.md +330 -0
  56. package/skills/geomaster/references/gis-software.md +369 -0
  57. package/skills/geomaster/references/industry-applications.md +420 -0
  58. package/skills/geomaster/references/machine-learning.md +462 -0
  59. package/skills/geomaster/references/programming-languages.md +456 -0
  60. package/skills/geomaster/references/remote-sensing.md +370 -0
  61. package/skills/geomaster/references/scientific-domains.md +416 -0
  62. package/skills/geomaster/references/specialized-topics.md +428 -0
  63. package/skills/geomaster/references/troubleshooting.md +439 -0
  64. package/skills/geomaster/skill.json +157 -0
  65. package/skills/geopandas/SKILL.md +250 -0
  66. package/skills/geopandas/UPSTREAM.md +22 -0
  67. package/skills/geopandas/references/crs-management.md +231 -0
  68. package/skills/geopandas/references/data-io.md +323 -0
  69. package/skills/geopandas/references/data-structures.md +207 -0
  70. package/skills/geopandas/references/geometric-operations.md +262 -0
  71. package/skills/geopandas/references/spatial-analysis.md +294 -0
  72. package/skills/geopandas/references/visualization.md +230 -0
  73. package/skills/geopandas/scripts/_common.py +605 -0
  74. package/skills/geopandas/scripts/crs_reprojection_plan.py +210 -0
  75. package/skills/geopandas/scripts/export_plan.py +305 -0
  76. package/skills/geopandas/scripts/geometry_validity_report.py +227 -0
  77. package/skills/geopandas/scripts/sensitive_coordinates_checklist.py +230 -0
  78. package/skills/geopandas/scripts/spatial_join_audit.py +368 -0
  79. package/skills/geopandas/scripts/vector_inventory.py +140 -0
  80. package/skills/geopandas/skill.json +116 -0
  81. package/skills/geoparquet-validation/SKILL.md +125 -0
  82. package/skills/geoparquet-validation/UPSTREAM.md +24 -0
  83. package/skills/geoparquet-validation/references/distribution-best-practices.md +118 -0
  84. package/skills/geoparquet-validation/references/gpio-commands.md +264 -0
  85. package/skills/geoparquet-validation/references/tool-comparison.md +155 -0
  86. package/skills/geoparquet-validation/skill.json +71 -0
  87. package/skills/geospatial-data-discovery/SKILL.md +49 -0
  88. package/skills/geospatial-data-discovery/UPSTREAM.md +15 -0
  89. package/skills/geospatial-data-discovery/skill.json +51 -0
  90. package/skills/geospatial-frontend/SKILL.md +86 -0
  91. package/skills/geospatial-frontend/UPSTREAM.md +23 -0
  92. package/skills/geospatial-frontend/references/design-system.md +283 -0
  93. package/skills/geospatial-frontend/references/user-preferences.md +96 -0
  94. package/skills/geospatial-frontend/skill.json +87 -0
  95. package/skills/geozarr/SKILL.md +244 -0
  96. package/skills/geozarr/UPSTREAM.md +21 -0
  97. package/skills/geozarr/skill.json +97 -0
  98. package/skills/networkx/SKILL.md +440 -0
  99. package/skills/networkx/UPSTREAM.md +22 -0
  100. package/skills/networkx/references/algorithms.md +384 -0
  101. package/skills/networkx/references/generators.md +385 -0
  102. package/skills/networkx/references/graph-basics.md +284 -0
  103. package/skills/networkx/references/io.md +457 -0
  104. package/skills/networkx/references/visualization.md +531 -0
  105. package/skills/networkx/skill.json +93 -0
  106. package/skills/raster-processing/SKILL.md +222 -0
  107. package/skills/raster-processing/UPSTREAM.md +7 -0
  108. package/skills/raster-processing/skill.json +81 -0
  109. package/skills/sar-basics/SKILL.md +202 -0
  110. package/skills/sar-basics/UPSTREAM.md +7 -0
  111. package/skills/sar-basics/references/calibration-lut.md +98 -0
  112. package/skills/sar-basics/skill.json +97 -0
  113. package/skills/satellite-preprocessing/SKILL.md +241 -0
  114. package/skills/satellite-preprocessing/UPSTREAM.md +7 -0
  115. package/skills/satellite-preprocessing/skill.json +84 -0
  116. package/skills/scientific-visualization/SKILL.md +285 -0
  117. package/skills/scientific-visualization/UPSTREAM.md +25 -0
  118. package/skills/scientific-visualization/assets/color_palettes.py +263 -0
  119. package/skills/scientific-visualization/assets/nature.mplstyle +68 -0
  120. package/skills/scientific-visualization/assets/presentation.mplstyle +68 -0
  121. package/skills/scientific-visualization/assets/publication.mplstyle +77 -0
  122. package/skills/scientific-visualization/assets/publisher_profiles.json +269 -0
  123. package/skills/scientific-visualization/references/color_palettes.md +227 -0
  124. package/skills/scientific-visualization/references/journal_requirements.md +169 -0
  125. package/skills/scientific-visualization/references/matplotlib_examples.md +336 -0
  126. package/skills/scientific-visualization/references/publication_guidelines.md +196 -0
  127. package/skills/scientific-visualization/references/sources.md +76 -0
  128. package/skills/scientific-visualization/scripts/_common.py +136 -0
  129. package/skills/scientific-visualization/scripts/export_plan.py +493 -0
  130. package/skills/scientific-visualization/scripts/figure_export.py +642 -0
  131. package/skills/scientific-visualization/scripts/image_metadata.py +731 -0
  132. package/skills/scientific-visualization/scripts/palette_audit.py +327 -0
  133. package/skills/scientific-visualization/scripts/style_presets.py +501 -0
  134. package/skills/scientific-visualization/scripts/style_preview.py +232 -0
  135. package/skills/scientific-visualization/skill.json +95 -0
  136. package/skills/spectral-indices/SKILL.md +235 -0
  137. package/skills/spectral-indices/UPSTREAM.md +7 -0
  138. package/skills/spectral-indices/skill.json +88 -0
  139. package/skills/stac-and-cloud-access/SKILL.md +209 -0
  140. package/skills/stac-and-cloud-access/UPSTREAM.md +7 -0
  141. package/skills/stac-and-cloud-access/references/run-manifest.md +94 -0
  142. package/skills/stac-and-cloud-access/skill.json +98 -0
  143. package/skills/statistical-analysis/SKILL.md +446 -0
  144. package/skills/statistical-analysis/UPSTREAM.md +24 -0
  145. package/skills/statistical-analysis/references/assumptions_and_diagnostics.md +379 -0
  146. package/skills/statistical-analysis/references/bayesian_statistics.md +686 -0
  147. package/skills/statistical-analysis/references/effect_sizes_and_power.md +649 -0
  148. package/skills/statistical-analysis/references/reporting_standards.md +482 -0
  149. package/skills/statistical-analysis/references/test_selection_guide.md +129 -0
  150. package/skills/statistical-analysis/scripts/assumption_checks.py +652 -0
  151. package/skills/statistical-analysis/skill.json +127 -0
  152. package/skills/systematic-debugging/SKILL.md +283 -0
  153. package/skills/systematic-debugging/UPSTREAM.md +28 -0
  154. package/skills/systematic-debugging/condition-based-waiting-example.ts +158 -0
  155. package/skills/systematic-debugging/condition-based-waiting.md +115 -0
  156. package/skills/systematic-debugging/defense-in-depth.md +122 -0
  157. package/skills/systematic-debugging/find-polluter.sh +72 -0
  158. package/skills/systematic-debugging/root-cause-tracing.md +169 -0
  159. package/skills/systematic-debugging/skill.json +88 -0
  160. package/skills/time-series-and-change/SKILL.md +217 -0
  161. package/skills/time-series-and-change/UPSTREAM.md +7 -0
  162. package/skills/time-series-and-change/references/change-methods.md +42 -0
  163. package/skills/time-series-and-change/skill.json +116 -0
  164. package/skills/vector-quality/SKILL.md +204 -0
  165. package/skills/vector-quality/UPSTREAM.md +7 -0
  166. package/skills/vector-quality/skill.json +82 -0
  167. package/skills/verification/SKILL.md +120 -0
  168. package/skills/verification/UPSTREAM.md +31 -0
  169. package/skills/verification/skill.json +67 -0
  170. package/skills/writing-plans/SKILL.md +171 -0
  171. package/skills/writing-plans/UPSTREAM.md +23 -0
  172. package/skills/writing-plans/plan-document-reviewer-prompt.md +49 -0
  173. package/skills/writing-plans/skill.json +80 -0
  174. package/sources/SOURCES.md +374 -0
  175. package/third_party/isaaccorley-geospatial-skills/LICENSE +176 -0
  176. package/third_party/isaaccorley-geospatial-skills/NOTICE.md +17 -0
  177. package/third_party/kdense-scientific-agent-skills/LICENSE +21 -0
  178. package/third_party/kdense-scientific-agent-skills/NOTICE.md +19 -0
  179. package/third_party/superpowers/LICENSE +21 -0
  180. package/third_party/superpowers/NOTICE.md +17 -0
  181. package/third_party/timescale-pg-aiguide/LICENSE +176 -0
  182. package/third_party/timescale-pg-aiguide/NOTICE.md +14 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Terraproof Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,357 @@
1
- # Temporary Holding Version
1
+ # Terraproof
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > evidence-graded skills, tools, and checks for mapping and remote-sensing AI agents. *By Geova.*
4
+
5
+ > **Status:** Experimental — refocusing from AgentLayer v0.1
6
+
7
+ Terraproof is a focused collection of mapping and remote-sensing skills for AI coding agents, plus a deterministic router that selects the smallest useful set of them for a task. The direction is to make geospatial agents prove their work: inspect real datasets, apply section-level expert guidance, run executable checks, and attach an evidence grade to each result. Read the full plan in [`Terraproof_v1_PLAN.md`](Terraproof_v1_PLAN.md).
8
+
9
+ **Today:** 24 skills, a TypeScript router with 73 test scenarios, and a Python package with dataset inspection, checks, evidence grades, a skill router, a read-only MCP server, executable evals, and agent installers (see [Python core](#python-core-phase-1-experimental), [Skill router (Python)](#skill-router-python), [MCP server](#mcp-server), and [Install into your agent](#install-into-your-agent)).
10
+ **Planned, not implemented yet:** verification of the installers in real agent hosts (only Claude Code has been exercised end to end) and a fresh, independently written held-out routing set.
11
+
12
+ ---
13
+
14
+ ## Quick Start: Route a Real Task
15
+
16
+ Use a source checkout for this walkthrough; it does not depend on an npm release being available.
17
+
18
+ **Requirements:** Git and Node.js. Source checkout commands (`node router/index.ts ...`) need **Node.js 22.18+ or 24+** for native TypeScript support (see [Node.js TypeScript support](https://nodejs.org/api/typescript.html)). The built package (`npm run build`, `node bin/terraproof.js ...`) needs Node.js 20+. No model API key is needed for routing. A coding agent is needed separately to implement the task.
19
+
20
+ ```bash
21
+ git clone https://github.com/esmailhussien/terraproof.git
22
+ cd terraproof
23
+ node router/index.ts --version
24
+ node router/index.ts validate
25
+ node router/index.ts route "Download Sentinel-2 imagery from a STAC catalog, compute NDVI, and map the change with MapLibre" --dry-run
26
+ ```
27
+
28
+ **Expected result:** `--version` prints `terraproof v0.4.0`, and `validate` reports the current generated registry and collections. The route prints the task, selected skills grouped by layer, and rationale. Exact scores and selections are input- and registry-dependent; dry-run output also lists dropped candidates. It does not create files or call a model.
29
+
30
+ The walkthrough is illustrative, not a recorded execution. Exact selections and scores depend on the prompt, overrides, and registry revision. The commands that run offline were checked against this checkout. The download, NDVI, and MapLibre steps need network access and data, so they are illustrative only.
31
+
32
+ ### Practical example: Sentinel-2 NDVI change map
33
+
34
+ The task needs satellite imagery, a spectral index, and a web map. First inspect the route above. If the recommendation misses a requirement, revise the prompt or use overrides.
35
+
36
+ Bundle the selected skills into one reviewable context file. The `--include` flags force four skills; the router also selects `spectral-indices` for the NDVI step, so the bundle holds five:
37
+
38
+ ```bash
39
+ node router/index.ts bundle "Download Sentinel-2 imagery from a STAC catalog, compute NDVI, and map the change with MapLibre" --include geospatial-data-discovery --include geomaster --include geospatial-frontend --include verification --out ndvi-context.md
40
+ ```
41
+
42
+ **Expected artifact:** `ndvi-context.md` in the current directory. The CLI prints `✓ Composed bundle written to: ndvi-context.md (5 skills, <N> bytes)`; the size in this checkout was 40130 bytes. The file starts with a header listing the task, the five skills, and their layers, then the universal engineering instructions and the skill text grouped by layer. Review it, then give it to your coding agent together with your project requirements. The file is instructions, not generated application code.
43
+
44
+ For agents that support project skill directories, export to a separate demo folder first. The `--dry-run` form prints the same recommendation with `Mode: DRY RUN (No changes made)` and writes nothing:
45
+
46
+ ```bash
47
+ node router/index.ts apply "Download Sentinel-2 imagery from a STAC catalog, compute NDVI, and map the change with MapLibre" --include geospatial-data-discovery --include geomaster --include geospatial-frontend --include verification --target ../terraproof-demo/.agents/skills --dry-run
48
+
49
+ # After reviewing the recommendation, remove --dry-run to write files:
50
+ node router/index.ts apply "Download Sentinel-2 imagery from a STAC catalog, compute NDVI, and map the change with MapLibre" --include geospatial-data-discovery --include geomaster --include geospatial-frontend --include verification --target ../terraproof-demo/.agents/skills
51
+ ```
52
+
53
+ **Expected files after a successful export** (the target is resolved from the directory you run the command in, so this folder appears next to the clone):
54
+
55
+ ```text
56
+ terraproof-demo/
57
+ └── .agents/
58
+ ├── AGENTS.md # Generated manifest with installed skills and rationales
59
+ ├── instructions/ # engineering.md, security.md, simplicity.md; copied only if this folder does not exist yet
60
+ └── skills/ # One folder per selected skill; UPSTREAM.md is excluded
61
+ ├── geomaster/
62
+ ├── geospatial-data-discovery/
63
+ ├── geospatial-frontend/
64
+ ├── spectral-indices/
65
+ └── verification/
66
+ ```
67
+
68
+ Check the CLI output for copy errors and inspect the files. The CLI reminds you that nothing loads these skills automatically, so reference `.agents/skills` from your agent's instruction file (for example, a root `AGENTS.md`). Then ask the agent to read the manifest and the relevant skills before it implements anything. Verify the resulting work yourself, including the map rendering and the error states in the app.
69
+
70
+ ### Check the result with the Python core
71
+
72
+ After the work produces a raster, run the Python checks on it. Setup (Python 3.10 or newer) and the full list of checks are in [Python core](#python-core-phase-1-experimental).
73
+
74
+ ```bash
75
+ python -m terraproof check ndvi.tif --expect index --format md --lang ar --out ndvi_report_ar.md
76
+ ```
77
+
78
+ `--expect index` checks that the sampled values fall within [-1, 1]. `--lang` only applies to the Markdown format, so `--format md --lang ar` writes an Arabic report. The exit code is `0` Decision-grade, `2` Review required, `3` Advisory only, or `1` for a usage error.
79
+
80
+ **Expected result (illustrative for `ndvi.tif`):** the grade and messages depend on your file. This command was run on a synthetic 64×64 NDVI GeoTIFF (EPSG:32636, striped, no overviews), not on a Sentinel-2 product. It produced the grade **يحتاج مراجعة** (Review required) and exit code `2`: `raster.cog_layout` warned that the file is not a tiled COG, while `crs.defined`, `raster.nodata_declared`, and `rs.index_range` passed.
81
+
82
+ ### Experimental limits and safe use
83
+
84
+ - Routing is deterministic keyword/scoring logic, not semantic understanding. Confidence is a routing signal, not a probability that the implementation will succeed.
85
+ - Inspect recommendations before use. Prompt wording, conflicts, collection presets, and manual overrides can change the selected skills.
86
+ - The CLI is strict. Unknown options, options missing a value, `--include` or `--exclude` names that are not registered skills, unknown `--collection` names, and `--format` values other than `json` or `table` exit with status `1` and a message. `--help` lists the options.
87
+ - `apply` writes without an interactive confirmation; there is no `--yes` flag. It overwrites files that have the same names in the target and the manifest next to it (`<target>/../AGENTS.md`). Start in a disposable folder, or commit or back up existing files first.
88
+ - The generated manifest tells you to reference the skills from your agent's instruction file, because nothing loads `.agents/skills/` automatically.
89
+ - Use `route --dry-run` or `apply --dry-run` to inspect without exporting. `bundle --out` writes its file even when `--dry-run` is supplied, and it overwrites an existing output file.
90
+ - Routing uses local files. Cloning, dependency installation, and any tools that individual skills describe may need network access or their own dependencies.
91
+ - Exporting skills does not install GDAL, Python packages, browser tooling, or other domain dependencies, and it does not prove that an agent loaded or followed the instructions.
92
+
93
+ For development checks, see [Verify your change](CONTRIBUTING.md#verify-your-change) in `CONTRIBUTING.md`.
94
+
95
+ ---
96
+
97
+ ## Install & Usage
98
+
99
+ The npm package name `terraproof` is not published yet, so `npx terraproof` does not work from the registry. From a clone:
100
+
101
+ ```bash
102
+ npm install # dev dependencies (TypeScript)
103
+ npm run build # compile router/ to dist/router/
104
+ node bin/terraproof.js route "Reproject a GeoTIFF to EPSG:3857 and build a COG with GDAL"
105
+ node bin/terraproof.js --version
106
+ ```
107
+
108
+ Requirements:
109
+ - **Installed package (`dist/`):** Node.js 20 or newer.
110
+ - **Development and tests from source** (`node router/index.ts`, `npm run test:router`, `npm run typecheck`): Node.js 22.18 or newer, which strips TypeScript types natively.
111
+ - `npm run test:package` packs the repository, installs the tarball into a temporary project, and runs the installed CLI.
112
+
113
+ ## Smart Skill Router
114
+
115
+ The router is deterministic and offline. It maps a task description to a short list of skills, each with a reason:
116
+
117
+ ```bash
118
+ # Calculate the recommended skill composition
119
+ node router/index.ts route "Reproject GeoTIFF elevation tiles to EPSG:4326 and build COGs"
120
+
121
+ # Seed the selection from a preset collection
122
+ node router/index.ts route "Design a PostGIS schema for GPS tracks" --collection gis
123
+
124
+ # Inspect the result without changes, or print JSON for tooling
125
+ node router/index.ts route "Compute NDVI change for 2020-2024" --dry-run --format json
126
+
127
+ # Check registry integrity
128
+ node router/index.ts validate
129
+ ```
130
+
131
+ For scoring weights, layers, and heuristics, see [`routing/ROUTER_DESIGN.md`](routing/ROUTER_DESIGN.md) and [`router/README.md`](router/README.md).
132
+
133
+ ---
134
+
135
+ ## Python core (Phase 1, experimental)
136
+
137
+ The Python package `terraproof` inspects geospatial datasets, runs deterministic checks, and writes an evidence report as JSON or Markdown (English or Arabic). It reads local files only and makes no network calls. `inspect` and `check` are not a port of the TypeScript router; the same package also provides the separate Python skill router, the MCP server, and the agent installers described in the next three sections. The `terraproof` npm command above is still the TypeScript router; the Python core runs as `python -m terraproof`.
138
+
139
+ Setup, from the repository root (Python 3.10 or newer):
140
+
141
+ ```bash
142
+ python -m venv .venv
143
+ .venv/bin/python -m pip install -e ".[dev]" # Windows: .venv\Scripts\python -m pip install -e ".[dev]"
144
+ .venv/bin/python -m pytest -q tests/python
145
+ ```
146
+
147
+ Examples (replace the paths with your own datasets):
148
+
149
+ ```bash
150
+ # Print the inspection of one dataset as JSON
151
+ python -m terraproof inspect data/parcels.gpkg
152
+
153
+ # Run the checks and print a JSON evidence report
154
+ python -m terraproof check data/parcels.gpkg --operation area
155
+
156
+ # Compare record counts with the input and write a Markdown report in Arabic
157
+ python -m terraproof check outputs/clip.gpkg --compare-to data/parcels.gpkg --format md --lang ar --out report_ar.md
158
+
159
+ # Categorical raster: nearest or mode resampling passes, bilinear fails
160
+ python -m terraproof check landcover.tif --categorical --resampling nearest --format md
161
+ ```
162
+
163
+ Inputs: vector (`.gpkg`, `.geojson`, `.json`, `.shp`, `.fgb`, `.parquet` where GDAL can read it), raster (`.tif`, `.tiff`, `.vrt`, `.jp2`), and local STAC Item JSON.
164
+
165
+ Checks cover CRS and units (`crs.defined`, `crs.consistent`, `crs.metric_operation`), geometry (`geometry.valid`, `geometry.non_empty`, `geometry.type_consistent`), record counts (`scope.record_count`), raster integrity (`raster.nodata_declared`, `raster.resampling`, `raster.grid_alignment`, `raster.cog_layout`), remote-sensing value ranges (`rs.reflectance_range`, `rs.index_range`), and STAC provenance (`stac.provenance`), with Phase4 processing, preflight, and reproducibility checks documented below. A check that does not apply to an input is left out; a check that applies but cannot run is reported as `not-run`.
166
+
167
+ ### Phase 4 preflight, processing, and provenance
168
+
169
+ Preflight validates a declared JSON plan before processing. Supported fields include `operation`, `target_crs`, explicit `reproject`, `resampling`, `categorical`, `combine`, declared `alignment`, `decode`, product `encoding`, `time_range`, `expect`, `measurement_units`, and explicit `unit_conversion`. `target_crs` alone never implies reprojection; `alignment:true` and unit conversion must be declared, and malformed or reversed STAC intervals do not pass.
170
+
171
+ ```bash
172
+ python -m terraproof preflight input.tif --plan plan.json
173
+ python -m terraproof check output.tif --reference-input input_dn.tif --encoding s2-l2a --manifest run.manifest.json
174
+ python -m terraproof manifest write --inputs input.tif --outputs output.tif --params plan.json --out run.manifest.json
175
+ python -m terraproof manifest verify run.manifest.json
176
+ ```
177
+
178
+ Manifest verification covers every contributing path: primary, compare, reference, QA, samples, and class-area files. `--require-provenance` makes an absent or failed manifest advisory; CLI and MCP use the same coverage and malformed-manifest behavior. Processing checks include exact-once scale application, cloud masking, temporal scope, SAR domain/geocoding, and area-adjusted accuracy. Optional router semantic retrieval is offline-only and falls back to lexical retrieval when its dependency/model is unavailable; candidate mode defaults to eight deterministic candidates for optional host-side selection.
179
+
180
+ ### Evidence grades
181
+
182
+ | Grade | Arabic label | Meaning |
183
+ |---|---|---|
184
+ | Decision-grade | جاهز للقرار | Every check in the run passed. |
185
+ | Review required | يحتاج مراجعة | At least one check warned; none failed and none could not run. |
186
+ | Advisory only | استرشادي فقط | At least one check failed or could not run (`not-run`). A run with no checks is also Advisory only. |
187
+
188
+ Exit codes: `0` Decision-grade, `2` Review required, `3` Advisory only, `1` usage error or unreadable input.
189
+
190
+ The grade describes the data path and the checks that ran. It is not a certification of survey, engineering, legal, or safety fitness.
191
+
192
+ Arabic Markdown reports translate the labels, headings, status words, and the limitation sentence. Check messages, file paths, check ids, and numbers stay as produced (messages are in English).
193
+
194
+ ---
195
+
196
+ ## Skill router (Python)
197
+
198
+ `python -m terraproof route` is the Python skill router (Phase 3). Given a task description, it returns the few skill sections worth reading, each with the reasons for its score. It is offline, deterministic, and lexical; there is no model call. Setup is the same as [Python core](#python-core-phase-1-experimental); text-only routing is dependency-light, because the inspectors load only when you pass `--data`.
199
+
200
+ How it ranks:
201
+
202
+ - **BM25 over skill sections.** Every section of `SKILL.md` and the reference files is indexed. A skill's score is its best-matching section plus a quarter of its second best, so a skill ranks on the passage that matches, not on its length.
203
+ - **Exact triggers.** The technology and capability phrases in each `skill.json` add deterministic boosts when they occur as whole phrases. A bare `map` is deliberately weak.
204
+ - **Explained data-aware rules.** With `--data`, each local dataset is inspected first: CRS, bands, dtype, scale/offset, geometry types, feature counts, STAC collection. The profile then adds or subtracts score, and the reason is printed. A geographic CRS under metric wording (area, buffer, distance, metres) promotes `crs-and-units`; an integer band with a non-identity scale/offset promotes `satellite-preprocessing`; several rasters promote `raster-processing`; a raster-only input penalises vector skills, and a vector-only input penalises raster skills; a print-figure request penalises the web-map skill; a STAC item already in hand for processing penalises the catalog-search skill.
205
+ - **Arabic and Egyptian dialect.** Text is normalized before matching: diacritics and tatweel are dropped, NFKC is applied, and `أ/إ/آ/ٱ → ا`, `ى → ي`, `ة → ه`. Attached conjunctions, prepositions, and articles are tried (`ال`, `وال`, `بال`, `لل`, `ف`, `ب`, `ل`, `و`), and a curated lexicon maps Arabic phrases, including Egyptian forms such as `نزل` (download) and `دور على` (look for), to English retrieval terms. Latin technical tokens (`Sentinel-2`, `SCL`, `NDVI`) are matched as written, which is how these prompts are usually typed.
206
+ - **Process skills are separate.** `brainstorming`, `writing-plans`, `systematic-debugging`, and `verification` are never mixed into the ranked domain skills. The `process` field lists the ones whose wording appears in the task, followed by `verification`.
207
+
208
+ CLI usage:
209
+
210
+ ```bash
211
+ python -m terraproof route "TASK" [--data PATH ...] [--top-k N] [--mode ranked|candidates] [--semantic] [--format json|md]
212
+ ```
213
+
214
+ `--data` takes one or more local datasets and can be repeated; `--top-k` defaults to 5 and `--format` to `json`. `--format md` prints a readable digest of the same result, and JSON stays the stable machine-readable form. The command exits `0` and writes nothing.
215
+
216
+ English example:
217
+
218
+ ```bash
219
+ python -m terraproof route "Mask clouds in Sentinel-2 L2A with the SCL band, then compute NDVI" --format json
220
+ ```
221
+
222
+ The result is deterministic for a fixed registry and input. Each reason names the matched section, lexical contributions, and any exact triggers that fired.
223
+
224
+ Arabic example:
225
+
226
+ ```bash
227
+ python -m terraproof route "اضبط scale و offset لصور Sentinel-2 L2A قبل حساب NDVI" --format md
228
+ ```
229
+
230
+ It reports `Language: ar` and shows the normalized Arabic expansion and selected sections. Only your task line and matched Arabic terms are Arabic: reasons and section excerpts remain the English skill text, and JSON keeps your prompt verbatim.
231
+
232
+ Evaluate a routing set with the bundled evaluator:
233
+
234
+ It prints JSON with `items`, `top_k`, recall, per-language recall, `must_not` violations, and every failing item, and exits `1` when mean recall is below `--min-recall` or a forbidden skill is ranked. `evals/routing/dev.jsonl` is the permitted tuning/regression set; independent held-out sets are not part of routine development or this acceptance run. The evaluator measures retrieval only, not agent performance.
235
+
236
+ Limits: this is lexical retrieval with hand-written rules, not semantic understanding. Candidate mode returns a deterministic recall-oriented list (default cap 8) for optional host-side selection; ranked mode retains its existing cap and thresholds. Dataset rules fire once per request and only from the keys the inspectors report, so a misleading or missing profile leads to a misleading boost.
237
+
238
+ ---
239
+
240
+ ## MCP server
241
+
242
+ The MCP server exposes the same inspectors, checks, skill sections, and router to any Model Context Protocol client, so an agent gets identical results whether it calls the CLI or a tool. It is read-only: it never writes files and never uses the network.
243
+
244
+ ```bash
245
+ python -m pip install -e ".[mcp]" # Windows: .venv\Scripts\python -m pip install -e ".[mcp]"
246
+ python -m terraproof.mcp # serve over stdio
247
+ ```
248
+
249
+ The `mcp` extra installs the official MCP Python SDK 2.x (`mcp>=2.3,<3`); the base install stays dependency-light, and `inspect`, `check`, and `route` keep working without it. Register the server in your client with a stdio entry whose command is the interpreter that has the package installed and whose arguments are `-m terraproof.mcp`, or let [`python -m terraproof.install --with-mcp`](#install-into-your-agent) write that entry for you.
250
+
251
+ Six tools:
252
+
253
+ - `preflight(paths, plan, lang?)` — validate a declared plan (a JSON object or local JSON file path) against inspected inputs and return the evidence report without running processing.
254
+ - `inspect_dataset(path)` — profile one local vector, raster, or STAC Item file: CRS and units, schema or bands, dtype, nodata, extent, resolution, and feature or pixel counts.
255
+ - `run_checks(paths, operation?, compare_to?, resampling?, categorical?, expect?, lang?, ...)` — run checks and return the grade, exit code, JSON report, and Markdown in `en` or `ar`. Phase 4 parameters are `reference_input`, `encoding`, `qa_path`, `qa_kind`, `time_range`, `sar_expect`, `accuracy_samples`, `class_areas`, `min_per_class`, `estimates_requested`, `manifest`, and `require_provenance`; CLI flags use hyphens, with `--qa` for `qa_path`. Samples accept CSV/JSON file paths (or records through MCP); class areas accept a JSON file path (or a mapping through MCP).
256
+ - `list_skills()` — list the registered skills with their layer, one-sentence explanation, section ids and titles, and the check ids they bear on.
257
+ - `load_section(skill, section_id)` — return one section's Markdown text, without reading the whole `SKILL.md`.
258
+ - `find_guidance(task, data_paths?, top_k?, mode?, semantic?)` — retrieve skill sections and inspect the given datasets; `mode="candidates"` provides host-selectable candidates and `semantic=true` enables the optional cached local model. This is the retrieval `python -m terraproof route` performs.
259
+
260
+ ---
261
+
262
+ ## Install into your agent
263
+
264
+ The installer writes Terraproof into one project in that agent's own format, instead of a shared `.agents/` folder:
265
+
266
+ ```bash
267
+ python -m terraproof.install --agent {claude,cursor,codex,gemini,copilot,opencode} --skills a,b --target DIR [--with-mcp] [--dry-run]
268
+ python -m terraproof.install --agent cursor --task "NDVI change for 2020-2024" --target DIR
269
+ ```
270
+
271
+ Give either `--skills` (comma-separated names from `routing/registry.json`) or `--task` (routed by the Python router), never both. `--target` must already exist. `--with-mcp` also registers the Terraproof MCP server, and `--dry-run` prints the planned writes and changes nothing. The command exits `0` on success and `1` for a usage error such as an unknown skill name or a missing target.
272
+
273
+ What each agent gets (`<skill>` stands for one selected skill):
274
+
275
+ | `--agent` | Skill files | MCP config with `--with-mcp` |
276
+ |---|---|---|
277
+ | `claude` | `.claude/skills/<skill>/` — the full skill folder | `.mcp.json` (`mcpServers`) |
278
+ | `cursor` | `.cursor/rules/terraproof-<skill>.mdc` — one rule per skill | `.cursor/mcp.json` (`mcpServers`) |
279
+ | `codex` | `.agents/skills/<skill>/` plus a block in `AGENTS.md` | `.codex/config.toml` (`[mcp_servers.terraproof]`) |
280
+ | `gemini` | a block in `GEMINI.md` with the skill text inline | `.gemini/settings.json` (`mcpServers`) |
281
+ | `copilot` | `.github/instructions/terraproof-<skill>.instructions.md` | `.vscode/mcp.json` (`servers`) |
282
+ | `opencode` | a block in `AGENTS.md` with the skill text inline | `opencode.json` (`mcp`) |
283
+
284
+ Every format above was checked against that agent's own documentation; the source URL is cited next to the writer in `src/terraproof/install/agents.py`.
285
+
286
+ Merge and idempotency: nothing is written outside `--target`. An existing JSON or TOML config is parsed and merged, so other servers, keys, and tables survive, and only the `terraproof` server entry is replaced. Markdown goes between agent-scoped markers (`<!-- terraproof:<agent>:begin -->` and `<!-- terraproof:<agent>:end -->`); a rerun replaces only that agent's block and leaves the rest of the file alone. If a legacy unscoped `<!-- terraproof:begin -->` / `<!-- terraproof:end -->` block exists, the installer migrates it to the current agent's scoped marker and prints a note. A rerun with the same inputs produces identical bytes, unchanged files are reported as `unchanged` and not rewritten, and the recorded MCP command is the interpreter that ran the installer. Skill copies skip `UPSTREAM.md` and `skill.json`.
287
+
288
+ Known limits:
289
+
290
+ - **Claude Code** (2.1.292) reads the generated `.mcp.json` and lists `terraproof`, but project MCP servers start as "Pending approval"; an interactive `claude` session is required to approve the server before it connects.
291
+ - **Codex CLI** (0.160.1) parses the generated `.codex/config.toml`, but only loads project-scoped config for trusted projects. Verified by copying the same TOML into an isolated `CODEX_HOME`: `codex mcp list` / `codex mcp get terraproof` show the stdio server correctly.
292
+ - **Gemini CLI** (0.62.0) reads the generated `.gemini/settings.json` and reports `terraproof` as a configured stdio server, but `gemini mcp list` suppresses all servers (project and user-level) in an untrusted folder. Trusting the workspace is required to list, enable, or connect to the server.
293
+ - The other three agents (`cursor`, `copilot`, `opencode`) are unit-tested against their documented file layouts (`tests/python/test_install.py`); they have not been loaded by those agents here.
294
+ - Writing the files does not prove the host loaded them or that the agent followed the guidance. Verify an installed setup in the agent itself, as you would verify any agent-generated work.
295
+
296
+ ---
297
+
298
+ ## Skills (v0.2.0)
299
+
300
+ ### Process & Verification
301
+ - `brainstorming` — Explore intent, requirements, and design options before implementation.
302
+ - `writing-plans` — Produce detailed, executable task-by-task engineering plans.
303
+ - `systematic-debugging` — Structured root-cause investigation for bugs and errors.
304
+ - `verification` — Validate completeness and truthfulness before declaring work done.
305
+
306
+ ### Mapping & GIS
307
+ - `gdal` — Raster and vector CLI recipes: reprojection, clipping, mosaics, and COGs.
308
+ - `design-postgis-tables` — PostGIS table design, geometry vs geography, spatial indexing.
309
+ - `geoparquet-validation` — GeoParquet metadata validation and cloud-native vector distribution.
310
+ - `geospatial-frontend` — MapLibre GL and geospatial visualization interfaces.
311
+ - `crs-and-units` — Coordinate reference systems, axis order, datum transformations, and measurement units.
312
+ - `raster-processing` — Raster reading, grid alignment, resampling, nodata and masks, and COG delivery checks.
313
+
314
+ ### Remote Sensing & Earth Observation
315
+ - `geomaster` — Earth observation, satellite processing, spectral indices, terrain, and spatial ML.
316
+ - `geospatial-data-discovery` — Open geospatial data acquisition (STAC, OSM, Overture, Sentinel, Landsat, DEMs).
317
+ - `geozarr` — Multidimensional geospatial raster and cube arrays.
318
+ - `satellite-preprocessing` — Sentinel-2 L2A and Landsat Collection 2 surface reflectance decoding, QA masks, and composites.
319
+ - `spectral-indices` — NDVI, NDWI/MNDWI, NBR/dNBR, EVI, and SAVI from calibrated, masked reflectance.
320
+
321
+ ### Spatial Analysis & Visualization
322
+ - `geopandas` — Vector operations, spatial joins, geometric overlays, and CRS transforms.
323
+ - `vector-quality` — Geometry validity and repair, duplicate and coverage audits, and join cardinality checks.
324
+ - `scientific-visualization` — Publication-ready figures with colorblind-safe palettes and multi-panel layouts.
325
+ - `statistical-analysis` — Hypothesis testing, assumption diagnostics, effect sizes, and power analysis.
326
+ - `networkx` — Graph structures, centrality, community detection, and shortest paths.
327
+
328
+ ---
329
+
330
+ ## Preset Collections
331
+
332
+ | Collection | Description | Included Skills |
333
+ |---|---|---|
334
+ | `gis` | Geospatial engineering and mapping | `geomaster`, `geopandas`, `gdal`, `geospatial-data-discovery`, `verification` |
335
+ | `data-analysis` | Statistical modeling and scientific figures | `statistical-analysis`, `scientific-visualization`, `verification` |
336
+ | `production` | Core engineering discipline and debugging | `brainstorming`, `writing-plans`, `systematic-debugging`, `verification` |
337
+ | `remote-sensing` | Optical satellite preprocessing, spectral indices, raster processing, and verification | `geospatial-data-discovery`, `satellite-preprocessing`, `spectral-indices`, `raster-processing`, `verification` |
338
+
339
+ ---
340
+
341
+ ## Repository Overview
342
+
343
+ - **`skills/`** — Task-specific instructions, scripts, and references (24 skills, each with a `skill.json` routing manifest).
344
+ - **`routing/`** — Skill registry generated from `skills/*/skill.json`, check catalog, scoring rules, and preset collections.
345
+ - **`router/`** — Deterministic TypeScript routing engine with CLI and programmatic API.
346
+ - **`evals/`** — 27 executable benchmark task specifications plus the deterministic harness and permitted routing regression set `evals/routing/dev.jsonl`, scored by `python -m terraproof.router.evaluate`.
347
+ - **`src/terraproof/`** — Python package: dataset inspectors, checks, evidence reports, the skill router and its evaluator, the read-only MCP server, and the native agent installers (`pyproject.toml`).
348
+ - **`instructions/`** — Universal engineering rules (engineering discipline, simplicity, security).
349
+ - **`tests/`** — Router test suites (73 scenarios), Python tests for the checks, router, MCP server, evals, and installers (`tests/python/`), and upstream fixtures.
350
+ - **`third_party/`** — Upstream licenses and notices for vendored material.
351
+ - **`sources/`** — Attribution log mapping each skill to its upstream source, commit SHA, and license.
352
+
353
+ ---
354
+
355
+ ## License
356
+
357
+ This project is licensed under the [MIT License](LICENSE). Vendored and adapted components keep their upstream licenses (MIT, Apache-2.0, 3-clause BSD) as documented in `third_party/` and `sources/SOURCES.md`.
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import { runCli } from "../dist/router/index.js";
3
+
4
+ runCli();
@@ -0,0 +1,147 @@
1
+ import * as fs from "fs";
2
+ import * as path from "path";
3
+ function copySkillDir(srcDir, destDir) {
4
+ if (!fs.existsSync(destDir)) {
5
+ fs.mkdirSync(destDir, { recursive: true });
6
+ }
7
+ const entries = fs.readdirSync(srcDir, { withFileTypes: true });
8
+ for (const entry of entries) {
9
+ // Skip internal provenance files that consumers don't need
10
+ if (entry.name === "UPSTREAM.md")
11
+ continue;
12
+ const srcPath = path.join(srcDir, entry.name);
13
+ const destPath = path.join(destDir, entry.name);
14
+ if (entry.isDirectory()) {
15
+ copySkillDir(srcPath, destPath);
16
+ }
17
+ else {
18
+ fs.copyFileSync(srcPath, destPath);
19
+ }
20
+ }
21
+ }
22
+ export function applySkills(result, targetDir = ".agents/skills", workspaceRoot = process.cwd(), packageRoot = workspaceRoot) {
23
+ const resolvedTarget = path.resolve(workspaceRoot, targetDir);
24
+ const appliedSkills = [];
25
+ const errors = [];
26
+ if (!fs.existsSync(resolvedTarget)) {
27
+ fs.mkdirSync(resolvedTarget, { recursive: true });
28
+ }
29
+ for (const skill of result.skills) {
30
+ const srcDir = path.resolve(packageRoot, skill.path);
31
+ const destDir = path.resolve(resolvedTarget, skill.name);
32
+ if (!fs.existsSync(srcDir)) {
33
+ errors.push(`Skill directory not found on disk: ${srcDir}`);
34
+ continue;
35
+ }
36
+ try {
37
+ copySkillDir(srcDir, destDir);
38
+ appliedSkills.push(skill.name);
39
+ }
40
+ catch (err) {
41
+ errors.push(`Failed to copy skill '${skill.name}': ${err.message}`);
42
+ }
43
+ }
44
+ // Copy universal instructions
45
+ let instructionsCopied = false;
46
+ const srcInstructions = path.resolve(packageRoot, "instructions");
47
+ const destInstructions = path.resolve(resolvedTarget, "..", "instructions");
48
+ if (fs.existsSync(srcInstructions) && !fs.existsSync(destInstructions)) {
49
+ try {
50
+ fs.cpSync(srcInstructions, destInstructions, { recursive: true, force: true });
51
+ instructionsCopied = true;
52
+ }
53
+ catch {
54
+ // Non-fatal
55
+ }
56
+ }
57
+ // Write manifest file (.agents/AGENTS.md)
58
+ let manifestWritten = false;
59
+ try {
60
+ const manifestPath = path.resolve(resolvedTarget, "..", "AGENTS.md");
61
+ const manifest = generateManifest(result, appliedSkills);
62
+ fs.writeFileSync(manifestPath, manifest, "utf-8");
63
+ manifestWritten = true;
64
+ }
65
+ catch {
66
+ // Non-fatal
67
+ }
68
+ return {
69
+ targetDir: resolvedTarget,
70
+ appliedSkills,
71
+ instructionsCopied,
72
+ manifestWritten,
73
+ errors
74
+ };
75
+ }
76
+ function generateManifest(result, appliedSkills) {
77
+ const lines = [];
78
+ const now = new Date().toISOString().split("T")[0];
79
+ lines.push(`# Terraproof Skills Manifest`);
80
+ lines.push(``);
81
+ lines.push(`> Generated by Terraproof on ${now}`);
82
+ lines.push(`> Task: "${result.prompt}"`);
83
+ lines.push(`> Confidence: ${(result.confidence * 100).toFixed(0)}%`);
84
+ lines.push(``);
85
+ lines.push(`## Installed Skills (${appliedSkills.length})`);
86
+ lines.push(``);
87
+ for (const skill of result.skills) {
88
+ if (appliedSkills.includes(skill.name)) {
89
+ lines.push(`### ${skill.name} (${skill.layer} layer)`);
90
+ lines.push(`- **Rationale:** ${skill.reason}`);
91
+ lines.push(`- **Path:** \`skills/${skill.name}/SKILL.md\``);
92
+ lines.push(``);
93
+ }
94
+ }
95
+ lines.push(`## Usage`);
96
+ lines.push(``);
97
+ lines.push(`The skills are in \`.agents/skills/\`. No agent loads them automatically; reference them from your agent's instruction file (for example, a root \`AGENTS.md\`).`);
98
+ lines.push(``);
99
+ lines.push(`To regenerate with different options:`);
100
+ lines.push("```bash");
101
+ lines.push(`npx terraproof apply "${result.prompt}"`);
102
+ lines.push("```");
103
+ lines.push(``);
104
+ return lines.join("\n");
105
+ }
106
+ export function bundleSkills(result, packageRoot = process.cwd(), includeInstructions = true) {
107
+ const sections = [];
108
+ sections.push(`# Terraproof Skills Bundle\n\n` +
109
+ `> **Task:** "${result.prompt}"\n` +
110
+ `> **Confidence:** ${(result.confidence * 100).toFixed(0)}%\n` +
111
+ `> **Selected Skills:** ${result.skills.map((s) => s.name).join(", ")}\n` +
112
+ `> **Layers:** ${[...new Set(result.skills.map((s) => s.layer))].join(", ")}\n`);
113
+ if (includeInstructions) {
114
+ const instructionsDir = path.resolve(packageRoot, "instructions");
115
+ if (fs.existsSync(instructionsDir)) {
116
+ sections.push(`## Universal Engineering Instructions\n`);
117
+ const files = fs.readdirSync(instructionsDir).filter((f) => f.endsWith(".md")).sort();
118
+ for (const file of files) {
119
+ const content = fs.readFileSync(path.join(instructionsDir, file), "utf-8");
120
+ sections.push(`### ${file.replace(/\.md$/, "")}\n\n${content}\n`);
121
+ }
122
+ }
123
+ }
124
+ // Group skills by layer in bundle output
125
+ const layerLabels = {
126
+ process: "Process & Planning",
127
+ domain: "Domain Knowledge",
128
+ implementation: "Implementation & Architecture",
129
+ risk: "Risk & Security Audit",
130
+ verification: "Testing & Verification"
131
+ };
132
+ const layers = ["process", "domain", "implementation", "risk", "verification"];
133
+ for (const layer of layers) {
134
+ const layerSkills = result.skills.filter((s) => s.layer === layer);
135
+ if (layerSkills.length === 0)
136
+ continue;
137
+ sections.push(`## ${layerLabels[layer] || layer}\n`);
138
+ for (const skill of layerSkills) {
139
+ const skillMdPath = path.resolve(packageRoot, skill.path, "SKILL.md");
140
+ if (fs.existsSync(skillMdPath)) {
141
+ const content = fs.readFileSync(skillMdPath, "utf-8");
142
+ sections.push(`### ${skill.name}\n*Rationale: ${skill.reason}*\n\n${content}\n`);
143
+ }
144
+ }
145
+ }
146
+ return sections.join("\n---\n\n");
147
+ }