terraproof 0.0.0-stage → 0.4.1

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
@@ -0,0 +1,111 @@
1
+ const INTENT_PATTERNS = {
2
+ build: [
3
+ /\b(build|implement|scaffold|develop)\b/i,
4
+ /\bcreate\s+(an?\s+)?(app|application|dashboard|feature|module|system|service|component|pipeline|stack|table|schema|server|page|ui|chatbot|agent)\b/i,
5
+ /\bintegrate\s+an?\s+(external|weather|rest|api|map)\b/i,
6
+ /\bfrom scratch\b/i,
7
+ /\bnew feature\b/i
8
+ ],
9
+ fix: [/\b(fix|debug|resolve|patch|troubleshoot|repair)\b/i, /\b(bug|error|crash|broken|fails?|failing|exception|issue|401|403|404|500)\b/i],
10
+ analyze: [/\b(analyze|analysis|profile|inspect|audit|evaluate|check|compare|explore|eda|extract)\b/i],
11
+ optimize: [/\b(optimize|performance|speed up|scale|indexing|pool|fast|slow queries|improve|enhance)\b/i],
12
+ design: [/\b(design|architecture|system design|schema design|design table|restructure|modularize|domain boundaries|refactor)\b/i, /\brefactor.*(into|modules|boundaries)/i],
13
+ integrate: [/\b(integrate|integration|connect|consume|webhook|client|fetch|uses?\s+.*api|external api)\b/i]
14
+ };
15
+ const DOMAIN_PATTERNS = {
16
+ geospatial: [/\b(gis|geospatial|spatial|geo|map|maps|maplibre|geopandas|gdal|ogr|geotiff|cog|geoparquet|geozarr|postgis|stac|sentinel|landsat|coordinates?|crs|epsg|shapefile|geojson|dem|elevation)\b/i],
17
+ data: [/\b(data|dataset|csv|tsv|dataframe|eda|exploratory|missing values?|distributions?|anomalies?|hypothesis|anova|t-test|p-value|regression|correlation|visualization|plot|chart|matplotlib|seaborn|networkx|graph|nodes?|edges?)\b/i],
18
+ frontend: [/\b(frontend|ui|ux|web|dashboard|react|next\.?js|component|page|css|style|layout|theme|dark mode|responsive|browser|chatbot|cypress|playwright)\b/i],
19
+ database: [/\b(database|db|postgres|postgresql|supabase|sql|tables?|schema|migrations?|rls|indexing|postgis|parameterized|sql queries|database queries|slow queries)\b/i],
20
+ api: [/\b(api|apis|rest|http|fetch|endpoint|webhooks?|openapi|swagger|rate limit|exponential backoff|public api|weather api|geocoding api|external api)\b/i],
21
+ ai: [/\b(ai|llm|agent|agents|assistant|chatbot|rag|embeddings?|generatetext|streamtext|prompt|prompts|model|models)\b/i],
22
+ security: [/\b(security|vulnerability|vulnerabilities|auth|authentication|authorization|token|jwt|secrets?|api key|injection|sql injection|xss|csrf|cve|credentials?|parameterized|checkout)\b/i],
23
+ qa: [/\b(test|testing|tests|unit test|integration test|e2e|browser test|tdd|playwright|cypress|jest|pytest)\b/i]
24
+ };
25
+ const TECHNOLOGY_PATTERNS = {
26
+ react: [/\breact\b/i, /\bnext\.?js\b/i, /\bjsx\b/i, /\btsx\b/i, /\bhooks\b/i],
27
+ supabase: [/\bsupabase\b/i],
28
+ postgres: [/\bpostgres(ql)?\b/i],
29
+ postgis: [/\bpostgis\b/i],
30
+ gdal: [/\bgdal\b/i, /\bogr(2ogr)?\b/i, /\bgdalwarp\b/i, /\bgdal_translate\b/i, /\bgeotiff\b/i, /\bcog\b/i],
31
+ geopandas: [/\bgeopandas\b/i, /\bgeodataframe\b/i, /\bshapefile\b/i, /\bgeopackage\b/i, /\bgeojson\b/i],
32
+ maplibre: [/\bmaplibre\b/i, /\bdeck\.?gl\b/i, /\bweb map\b/i, /\binteractive map\b/i, /\bmap\b/i],
33
+ networkx: [/\bnetworkx\b/i, /\bgraph analysis\b/i, /\bcentrality\b/i, /\bcommunity detection\b/i],
34
+ matplotlib: [/\bmatplotlib\b/i, /\bseaborn\b/i],
35
+ geoparquet: [/\bgeoparquet\b/i],
36
+ geozarr: [/\bgeozarr\b/i, /\bzarr\b/i],
37
+ "ai-sdk": [/\b(ai sdk|vercel ai|generatetext|streamtext|usechat|usecompletion|toolloopagent|llm|chatbot|rag|embeddings?|ai agent|ai assistant|map assistant)\b/i]
38
+ };
39
+ const CAPABILITY_PATTERNS = {
40
+ "web-map": [/\b(web map|interactive map|map dashboard|map interface|render map|map assistant|maplibre)\b/i],
41
+ "spatial-analysis": [/\b(spatial join|buffer|within \d+|overlay|proximity|nearest neighbor|distance)\b/i],
42
+ "raster-processing": [/\b(reproject|cog|geotiff|raster|mosaic|clip raster|warp)\b/i],
43
+ "vector-analysis": [/\b(vector|shapefile|geojson|geopackage|polygon|multipolygon|line|points?)\b/i],
44
+ "earth-observation": [/\b(satellite|sentinel|landsat|remote sensing|earth observation|ndvi)\b/i],
45
+ "data-profiling": [/\b(eda|exploratory|profile|missing values?|anomalies?|dataset summary)\b/i],
46
+ "statistical-testing": [/\b(hypothesis test|t-test|anova|significance|p-value|effect size|cohen's d)\b/i],
47
+ "data-visualization": [/\b(plot|chart|figure|publication-quality|multi-panel|scientific visual)\b/i],
48
+ "graph-analysis": [/\b(graph|network|centrality|community|shortest path|nodes? and edges?)\b/i],
49
+ "api-discovery": [/\b(find apis?|search apis?|free apis?|public apis?|recommend apis?|discover apis?|geocoding apis?)\b/i],
50
+ "api-integration": [/\b(integrate api|api client|rest client|fetch wrapper|rate limit|exponential backoff|webhook|api as a tool|uses?\s+(a\s+)?.*api|external api)\b/i],
51
+ "database-schema": [/\b(design table|create table|migrations?|table design|indexes|rls)\b/i],
52
+ "ai-chat": [/\b(chatbot|chat completions?|conversational ai|chat history|ai assistant|map assistant)\b/i],
53
+ "ai-streaming": [/\b(streaming ai|stream text|streaming)\b/i],
54
+ "structured-output": [/\b(structured output|json schema|extract.*fields|validated (json )?schema)\b/i],
55
+ "tool-calling": [/\b(tool calling|tool loop|tools?|function calling|destructive actions?|approval before|api as a tool)\b/i],
56
+ "rag": [/\b(rag|retrieval augmented|embeddings?|vector search|document search|pdfs?)\b/i]
57
+ };
58
+ const TRIVIAL_PATTERNS = [
59
+ /\b(button label|rename|typo|fix typo|change text|change color|button text|spelling|page heading|heading text|rename.*heading|copyright text)\b/i
60
+ ];
61
+ const RISK_PATTERNS = [
62
+ /\b(auth|login|token|jwt|secret|api key|password|credential|payment|stripe|private data|pii|rls|vulnerability|injection|cve|upload(ed|ing)?|permission|approval|destructive|delete data|api as a tool|external api|parameterized|checkout)\b/i
63
+ ];
64
+ export function classifyTask(prompt) {
65
+ const normalized = prompt.trim();
66
+ const intents = [];
67
+ for (const [intent, regexes] of Object.entries(INTENT_PATTERNS)) {
68
+ if (regexes.some((r) => r.test(normalized))) {
69
+ intents.push(intent);
70
+ }
71
+ }
72
+ const domains = [];
73
+ for (const [domain, regexes] of Object.entries(DOMAIN_PATTERNS)) {
74
+ if (regexes.some((r) => r.test(normalized))) {
75
+ domains.push(domain);
76
+ }
77
+ }
78
+ const technologies = [];
79
+ for (const [tech, regexes] of Object.entries(TECHNOLOGY_PATTERNS)) {
80
+ if (regexes.some((r) => r.test(normalized))) {
81
+ technologies.push(tech);
82
+ }
83
+ }
84
+ const capabilities = [];
85
+ for (const [cap, regexes] of Object.entries(CAPABILITY_PATTERNS)) {
86
+ if (regexes.some((r) => r.test(normalized))) {
87
+ capabilities.push(cap);
88
+ }
89
+ }
90
+ const isTrivial = TRIVIAL_PATTERNS.some((r) => r.test(normalized)) && !intents.includes("build");
91
+ const hasRiskBoundary = RISK_PATTERNS.some((r) => r.test(normalized));
92
+ const needsBrowserTesting = domains.includes("frontend") || technologies.includes("react") || capabilities.includes("web-map") || capabilities.includes("ai-chat") || /\b(cypress|playwright)\b/i.test(normalized);
93
+ const needsIntegrationTesting = domains.includes("database") || domains.includes("api") || technologies.includes("supabase") || technologies.includes("postgres") || intents.includes("fix") || capabilities.includes("tool-calling") || capabilities.includes("rag");
94
+ const needsUnitTesting = domains.includes("data") ||
95
+ capabilities.includes("statistical-testing") ||
96
+ capabilities.includes("graph-analysis") ||
97
+ capabilities.includes("structured-output") ||
98
+ /\b(unit\s*tests?|math\s+function|isolated\s+function|generatetext|fallback providers)\b/i.test(normalized);
99
+ return {
100
+ rawPrompt: normalized,
101
+ intents,
102
+ domains,
103
+ technologies,
104
+ capabilities,
105
+ isTrivial,
106
+ hasRiskBoundary,
107
+ needsBrowserTesting,
108
+ needsIntegrationTesting,
109
+ needsUnitTesting
110
+ };
111
+ }
@@ -0,0 +1,9 @@
1
+ export function generateSkillExplanation(skill, classification, reasons, isAutoInjected = false) {
2
+ if (reasons.some((r) => r.includes("Explicitly included"))) {
3
+ return "Explicitly requested by manual --include override.";
4
+ }
5
+ if (skill.explanation) {
6
+ return skill.explanation;
7
+ }
8
+ return reasons.length > 0 ? reasons.join("; ") : "Selected based on domain matching.";
9
+ }
@@ -0,0 +1,272 @@
1
+ import * as fs from "fs";
2
+ import * as path from "path";
3
+ import { fileURLToPath } from "url";
4
+ import { resolveRoute } from "./resolve.js";
5
+ import { validateRegistry } from "./validate.js";
6
+ import { applySkills, bundleSkills } from "./apply.js";
7
+ export { applySkills, bundleSkills };
8
+ const __filename = fileURLToPath(import.meta.url);
9
+ const __dirname = path.dirname(__filename);
10
+ // Walk up to the package root. From source this file lives in router/ (root is one level up);
11
+ // from the compiled build it lives in dist/router/ (root is two levels up).
12
+ function findPackageRoot(startDir) {
13
+ let dir = startDir;
14
+ for (;;) {
15
+ if (fs.existsSync(path.join(dir, "package.json")) && fs.existsSync(path.join(dir, "routing", "registry.json"))) {
16
+ return dir;
17
+ }
18
+ const parent = path.dirname(dir);
19
+ if (parent === dir) {
20
+ throw new Error(`Terraproof package root not found above ${startDir}`);
21
+ }
22
+ dir = parent;
23
+ }
24
+ }
25
+ const workspaceRoot = findPackageRoot(__dirname);
26
+ export function loadRoutingData(baseDir = workspaceRoot) {
27
+ const registryPath = path.join(baseDir, "routing", "registry.json");
28
+ const collectionsPath = path.join(baseDir, "routing", "collections.json");
29
+ const rulesPath = path.join(baseDir, "routing", "rules.json");
30
+ const registry = JSON.parse(fs.readFileSync(registryPath, "utf-8"));
31
+ const collections = JSON.parse(fs.readFileSync(collectionsPath, "utf-8"));
32
+ const rules = JSON.parse(fs.readFileSync(rulesPath, "utf-8"));
33
+ return { registry, collections, rules };
34
+ }
35
+ export function route(prompt, options = {}, baseDir = workspaceRoot) {
36
+ const { registry, collections, rules } = loadRoutingData(baseDir);
37
+ return resolveRoute(prompt, registry, collections, rules, options);
38
+ }
39
+ export function printRouteResult(result, format = "table") {
40
+ if (format === "json") {
41
+ console.log(JSON.stringify(result, null, 2));
42
+ return;
43
+ }
44
+ console.log("\n================================================================================");
45
+ console.log(" Terraproof Smart Skill Router");
46
+ console.log("================================================================================");
47
+ console.log(`Task Prompt : "${result.prompt}"`);
48
+ console.log(`Confidence : ${(result.confidence * 100).toFixed(0)}%`);
49
+ console.log(`Selected : ${result.skills.length} skill(s)`);
50
+ if (result.dryRun) {
51
+ console.log(`Mode : DRY RUN (No changes made)`);
52
+ }
53
+ console.log("--------------------------------------------------------------------------------");
54
+ if (result.warning) {
55
+ console.log(`\n⚠️ ${result.warning}`);
56
+ }
57
+ const layerLabels = {
58
+ process: "1. Process & Planning",
59
+ domain: "2. Domain Knowledge",
60
+ implementation: "3. Implementation & Architecture",
61
+ risk: "4. Risk & Security Audit",
62
+ verification: "5. Testing & Verification"
63
+ };
64
+ const layers = ["process", "domain", "implementation", "risk", "verification"];
65
+ for (const layer of layers) {
66
+ const skillsInLayer = result.skillsByLayer[layer];
67
+ if (skillsInLayer.length > 0) {
68
+ console.log(`\n[ ${layerLabels[layer]} ]`);
69
+ for (const skill of skillsInLayer) {
70
+ console.log(` * ${skill.name.padEnd(30)} (Score: ${skill.score})`);
71
+ console.log(` -> ${skill.reason}`);
72
+ }
73
+ }
74
+ }
75
+ if (result.dryRun && result.dropped && result.dropped.length > 0) {
76
+ console.log("\n[ Diagnostic: Dropped / Suppressed Candidates ]");
77
+ for (const d of result.dropped.slice(0, 8)) {
78
+ console.log(` - ${d.skill.padEnd(30)}: ${d.reason}`);
79
+ }
80
+ }
81
+ console.log("\n================================================================================\n");
82
+ }
83
+ const FLAG_OPTIONS = ["--dry-run", "--apply", "-a", "--bundle", "-b"];
84
+ const VALUE_OPTIONS = ["--target", "--out", "--include", "--exclude", "--collection", "--format"];
85
+ // Pure argument parser: args are the raw CLI arguments with the command first.
86
+ // Returns the parsed options, or { error } describing the first invalid input.
87
+ export function parseCliArgs(args, registry, collections) {
88
+ const command = args[0];
89
+ if (command !== "route" && command !== "apply" && command !== "bundle") {
90
+ return { error: `Unknown command '${command}'. Expected route, apply, bundle, or validate.` };
91
+ }
92
+ const prompt = args[1];
93
+ if (!prompt || prompt.startsWith("-")) {
94
+ return { error: "Please provide a task description string." };
95
+ }
96
+ const include = [];
97
+ const exclude = [];
98
+ const parsed = {
99
+ command,
100
+ prompt,
101
+ options: { include, exclude, dryRun: false },
102
+ format: "table",
103
+ doApply: command === "apply",
104
+ doBundle: command === "bundle",
105
+ targetDir: ".agents/skills"
106
+ };
107
+ for (let i = 2; i < args.length; i++) {
108
+ const arg = args[i];
109
+ if (FLAG_OPTIONS.includes(arg)) {
110
+ if (arg === "--dry-run") {
111
+ parsed.options.dryRun = true;
112
+ }
113
+ else if (arg === "--apply" || arg === "-a") {
114
+ parsed.doApply = true;
115
+ }
116
+ else {
117
+ parsed.doBundle = true;
118
+ }
119
+ continue;
120
+ }
121
+ if (VALUE_OPTIONS.includes(arg)) {
122
+ const value = args[i + 1];
123
+ if (!value || value.startsWith("-")) {
124
+ return { error: `Option ${arg} requires a value.` };
125
+ }
126
+ i++;
127
+ if (arg === "--target") {
128
+ parsed.targetDir = value;
129
+ }
130
+ else if (arg === "--out") {
131
+ parsed.outFile = value;
132
+ }
133
+ else if (arg === "--include" || arg === "--exclude") {
134
+ if (!Object.hasOwn(registry.skills, value)) {
135
+ return { error: `Unknown skill '${value}' for ${arg}. Registered skills are listed in routing/registry.json.` };
136
+ }
137
+ if (arg === "--include") {
138
+ include.push(value);
139
+ }
140
+ else {
141
+ exclude.push(value);
142
+ }
143
+ }
144
+ else if (arg === "--collection") {
145
+ if (!Object.hasOwn(collections.collections, value)) {
146
+ const available = Object.keys(collections.collections).join(", ");
147
+ return { error: `Unknown collection '${value}'. Available collections: ${available}.` };
148
+ }
149
+ parsed.options.collection = value;
150
+ }
151
+ else {
152
+ if (value !== "json" && value !== "table") {
153
+ return { error: `Invalid --format '${value}'. Use json or table.` };
154
+ }
155
+ parsed.format = value;
156
+ }
157
+ continue;
158
+ }
159
+ if (arg.startsWith("-")) {
160
+ return { error: `Unknown option '${arg}'.` };
161
+ }
162
+ return { error: `Unexpected argument '${arg}'. Put the task description in quotes, then options.` };
163
+ }
164
+ return parsed;
165
+ }
166
+ export function runCli(args = process.argv.slice(2)) {
167
+ if (args.includes("--version") || args.includes("-v")) {
168
+ const pkgPath = path.join(workspaceRoot, "package.json");
169
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
170
+ console.log(`terraproof v${pkg.version}`);
171
+ process.exit(0);
172
+ }
173
+ if (args.length === 0 || args.includes("--help") || args.includes("-h")) {
174
+ console.log(`
175
+ Terraproof Smart Router & Skills CLI
176
+
177
+ Usage:
178
+ terraproof route "<task>" [options]
179
+ terraproof apply "<task>" [options]
180
+ terraproof bundle "<task>" [options]
181
+ terraproof validate
182
+ node router/index.ts route "<task>" [options] (from a source checkout)
183
+
184
+ Commands:
185
+ route "<prompt>" Calculate optimal skill composition for a task
186
+ apply "<prompt>" Calculate and copy selected skills to target (.agents/skills)
187
+ bundle "<prompt>" Output concatenated markdown of instructions & selected skills
188
+ validate Verify skill registry integrity and disk paths
189
+
190
+ Options:
191
+ --apply, -a Install/copy selected skills to target directory
192
+ --target <dir> Target directory for skills (default: .agents/skills)
193
+ --bundle, -b Generate unified markdown prompt/context
194
+ --out <file> Write bundled markdown output to file
195
+ --dry-run Display recommendation without modifying project
196
+ --include <skill> Force inclusion of a specific skill (can repeat)
197
+ --exclude <skill> Force exclusion of a specific skill (can repeat)
198
+ --collection <name> Seed from a preset collection (gis, data-analysis, production, remote-sensing)
199
+ --format <json|table> Output format (default: table)
200
+ --version, -v Show version number
201
+ --help, -h Show this help message
202
+
203
+ Examples:
204
+ terraproof route "Reproject a GeoTIFF to EPSG:3857 and build a COG with GDAL"
205
+ terraproof apply "Design a PostGIS schema for GPS tracks"
206
+ terraproof bundle "Compute NDVI change for 2020-2024" --out context.md
207
+ node router/index.ts route "Compute NDVI change for 2020-2024" --dry-run
208
+ `);
209
+ process.exit(0);
210
+ }
211
+ const command = args[0];
212
+ if (command === "validate") {
213
+ if (args.length > 1) {
214
+ console.error(`Error: 'validate' takes no options (unexpected '${args[1]}').`);
215
+ process.exit(1);
216
+ }
217
+ console.log("Validating Terraproof skill registry...");
218
+ const report = validateRegistry(workspaceRoot);
219
+ if (report.valid) {
220
+ console.log(`✓ Registry validation passed: ${report.skillsCount} skills, ${report.collectionsCount} collections.`);
221
+ process.exit(0);
222
+ }
223
+ else {
224
+ console.error(`✗ Registry validation failed with ${report.errors.length} error(s):`);
225
+ for (const err of report.errors) {
226
+ console.error(` - ${err}`);
227
+ }
228
+ process.exit(1);
229
+ }
230
+ }
231
+ const { registry, collections } = loadRoutingData(workspaceRoot);
232
+ const parsed = parseCliArgs(args, registry, collections);
233
+ if ("error" in parsed) {
234
+ console.error(`Error: ${parsed.error}`);
235
+ process.exit(1);
236
+ }
237
+ const result = route(parsed.prompt, parsed.options);
238
+ if (parsed.doBundle) {
239
+ const bundle = bundleSkills(result, workspaceRoot, true);
240
+ if (parsed.outFile) {
241
+ fs.writeFileSync(path.resolve(process.cwd(), parsed.outFile), bundle, "utf-8");
242
+ console.log(`✓ Composed bundle written to: ${parsed.outFile} (${result.skills.length} skills, ${bundle.length} bytes)`);
243
+ }
244
+ else {
245
+ console.log(bundle);
246
+ }
247
+ return;
248
+ }
249
+ printRouteResult(result, parsed.format);
250
+ if (parsed.doApply && !parsed.options.dryRun) {
251
+ console.log(`\nApplying ${result.skills.length} skill(s) to '${parsed.targetDir}'...`);
252
+ const applyRes = applySkills(result, parsed.targetDir, process.cwd(), workspaceRoot);
253
+ if (applyRes.errors.length > 0) {
254
+ console.error(`⚠️ Some skills had errors during install:`);
255
+ for (const err of applyRes.errors) {
256
+ console.error(` - ${err}`);
257
+ }
258
+ }
259
+ console.log(`✓ Installed ${applyRes.appliedSkills.length} skill(s) to '${applyRes.targetDir}'.`);
260
+ if (applyRes.instructionsCopied) {
261
+ console.log(`✓ Copied universal engineering instructions.`);
262
+ }
263
+ if (applyRes.manifestWritten) {
264
+ console.log(`✓ Generated skills manifest (AGENTS.md).`);
265
+ }
266
+ console.log(`\nNothing loads these skills automatically. Reference '${applyRes.targetDir}' from your agent's instruction file (for example, a root AGENTS.md).`);
267
+ }
268
+ }
269
+ // CLI auto-run when invoked directly
270
+ if (process.argv[1] && path.resolve(process.argv[1]) === path.resolve(__filename)) {
271
+ runCli();
272
+ }
@@ -0,0 +1,239 @@
1
+ import { classifyTask } from "./classify.js";
2
+ import { scoreSkill } from "./score.js";
3
+ import { generateSkillExplanation } from "./explain.js";
4
+ export function resolveRoute(prompt, registry, collections, rules, options = {}) {
5
+ const classification = classifyTask(prompt);
6
+ const minScore = options.minScore ?? rules.thresholds.selectionMinimumScore;
7
+ const scoredSkills = new Map();
8
+ const selectedMap = new Map();
9
+ const dropped = [];
10
+ // 1. Initial Scoring for all skills
11
+ for (const [name, skill] of Object.entries(registry.skills)) {
12
+ const scored = scoreSkill(skill, classification, options, rules);
13
+ scoredSkills.set(name, scored);
14
+ }
15
+ // 2. Preset Collection inclusion if specified
16
+ if (options.collection && collections.collections[options.collection]) {
17
+ const collection = collections.collections[options.collection];
18
+ for (const skillName of collection.base) {
19
+ if (registry.skills[skillName]) {
20
+ selectSkill(skillName, `Included from preset collection '${options.collection}'`, 25);
21
+ }
22
+ }
23
+ }
24
+ // 3. Process Layer selection based on intent
25
+ if (!classification.isTrivial) {
26
+ if (classification.intents.includes("fix")) {
27
+ selectSkill("systematic-debugging", "Fix/debug intent detected", 15);
28
+ }
29
+ else if (classification.intents.includes("build") || classification.intents.includes("design")) {
30
+ selectSkill("brainstorming", "New feature/system creation intent", 12);
31
+ selectSkill("writing-plans", "Detailed execution breakdown needed", 10);
32
+ }
33
+ }
34
+ // 4. Score threshold matching for Domain & Implementation skills
35
+ for (const [name, scored] of scoredSkills.entries()) {
36
+ if (scored.score >= minScore) {
37
+ const skill = registry.skills[name];
38
+ if (skill.layer === "domain" || skill.layer === "implementation" || skill.layer === "verification") {
39
+ const hasDirectSignal = scored.reasons.some((r) => r.includes("technology") || r.includes("Capability") || r.includes("Trigger") || r.includes("Keyword") || r.includes("override") || r.includes("collection"));
40
+ if (hasDirectSignal) {
41
+ selectSkill(name, scored.reasons.join("; "), scored.score);
42
+ }
43
+ else {
44
+ dropped.push({ skill: name, reason: `Broad domain match without specific capability/trigger hit (score: ${scored.score})` });
45
+ }
46
+ }
47
+ }
48
+ else if (scored.score > 0) {
49
+ dropped.push({ skill: name, reason: `Score ${scored.score} below minimum threshold ${minScore}` });
50
+ }
51
+ }
52
+ // 5. Risk Layer selection (Security Review)
53
+ if (classification.hasRiskBoundary && !classification.isTrivial) {
54
+ selectSkill("security-review", "Security/auth boundary or sensitive data detected", 12);
55
+ }
56
+ // 6. Verification Layer selection (Contextual)
57
+ if (classification.needsBrowserTesting) {
58
+ selectSkill("browser-testing", "Interactive UI / browser flow detected", 8);
59
+ }
60
+ if (classification.needsIntegrationTesting) {
61
+ selectSkill("integration-testing", "API/database or service boundary testing needed", 8);
62
+ }
63
+ if (classification.needsUnitTesting) {
64
+ selectSkill("unit-testing", "Data algorithms / function verification needed", 8);
65
+ }
66
+ // Universal completion verification
67
+ selectSkill("verification", "Universal completion and truthfulness audit", 10);
68
+ // 7. Apply recommended dependencies for high-confidence selected skills
69
+ const currentSelected = Array.from(selectedMap.keys());
70
+ for (const name of currentSelected) {
71
+ const skill = registry.skills[name];
72
+ if (skill && skill.recommended) {
73
+ for (const rec of skill.recommended) {
74
+ if (!selectedMap.has(rec) && registry.skills[rec]) {
75
+ const recSkill = registry.skills[rec];
76
+ const recScore = scoredSkills.get(rec)?.score || 0;
77
+ // Precision rule: Auto-add verification recommendations OR frontend-design when UI domain is active OR database best practices when database is active OR direct signal matches
78
+ const isUiDesignRec = rec === "frontend-design" && (classification.domains.includes("frontend") || classification.technologies.includes("react"));
79
+ const isDbRec = rec === "supabase-postgres-best-practices" && (classification.domains.includes("database") || classification.technologies.includes("postgres") || classification.technologies.includes("postgis"));
80
+ const isSecRec = rec === "security-review" && (classification.hasRiskBoundary || classification.domains.includes("security") || classification.domains.includes("api"));
81
+ if (recSkill.layer === "verification" || isUiDesignRec || isDbRec || isSecRec || recScore >= minScore) {
82
+ selectSkill(rec, `Recommended by ${name}`, Math.max(recScore, 6));
83
+ }
84
+ }
85
+ }
86
+ }
87
+ // Hard requires
88
+ if (skill && skill.requires) {
89
+ for (const req of skill.requires) {
90
+ if (!selectedMap.has(req) && registry.skills[req]) {
91
+ selectSkill(req, `Required dependency of ${name}`, 15);
92
+ }
93
+ }
94
+ }
95
+ }
96
+ // 8. Trivial task cleanup (suppress heavy planning, security review, and un-requested domain skills)
97
+ if (classification.isTrivial) {
98
+ for (const [sName, sObj] of Array.from(selectedMap.entries())) {
99
+ if (sName !== "verification" && (!options.include || !options.include.includes(sName))) {
100
+ selectedMap.delete(sName);
101
+ dropped.push({ skill: sName, reason: "Suppressed for trivial single-element edit task" });
102
+ }
103
+ }
104
+ }
105
+ // 9. Manual Exclusions
106
+ if (options.exclude) {
107
+ for (const excl of options.exclude) {
108
+ if (selectedMap.has(excl)) {
109
+ selectedMap.delete(excl);
110
+ dropped.push({ skill: excl, reason: "Explicitly excluded by user override" });
111
+ }
112
+ }
113
+ }
114
+ // 10. Deterministic Conflict Resolution
115
+ for (const [name, selected] of Array.from(selectedMap.entries())) {
116
+ const skill = registry.skills[name];
117
+ if (skill && skill.conflicts) {
118
+ for (const conf of skill.conflicts) {
119
+ if (selectedMap.has(conf)) {
120
+ const confSelected = selectedMap.get(conf);
121
+ // Deterministic winner selection:
122
+ // 1. Manual include
123
+ const nameIncluded = options.include?.includes(name);
124
+ const confIncluded = options.include?.includes(conf);
125
+ let winner = name;
126
+ let loser = conf;
127
+ if (nameIncluded && !confIncluded) {
128
+ winner = name;
129
+ loser = conf;
130
+ }
131
+ else if (confIncluded && !nameIncluded) {
132
+ winner = conf;
133
+ loser = name;
134
+ }
135
+ else if (selected.score !== confSelected.score) {
136
+ // 2. Higher score
137
+ if (selected.score > confSelected.score) {
138
+ winner = name;
139
+ loser = conf;
140
+ }
141
+ else {
142
+ winner = conf;
143
+ loser = name;
144
+ }
145
+ }
146
+ else {
147
+ // 3. Alphabetical tie-breaker for determinism
148
+ if (name < conf) {
149
+ winner = name;
150
+ loser = conf;
151
+ }
152
+ else {
153
+ winner = conf;
154
+ loser = name;
155
+ }
156
+ }
157
+ selectedMap.delete(loser);
158
+ dropped.push({ skill: loser, reason: `Dropped due to conflict with higher-priority skill '${winner}'` });
159
+ }
160
+ }
161
+ }
162
+ }
163
+ // 11. Group by Layer and Sort
164
+ const layerOrder = rules.layerOrder;
165
+ const skillsList = Array.from(selectedMap.values()).sort((a, b) => {
166
+ const layerA = layerOrder.indexOf(a.layer);
167
+ const layerB = layerOrder.indexOf(b.layer);
168
+ if (layerA !== layerB)
169
+ return layerA - layerB;
170
+ if (a.score !== b.score)
171
+ return b.score - a.score;
172
+ return a.name.localeCompare(b.name);
173
+ });
174
+ const skillsByLayer = {
175
+ process: [],
176
+ domain: [],
177
+ implementation: [],
178
+ risk: [],
179
+ verification: []
180
+ };
181
+ for (const s of skillsList) {
182
+ skillsByLayer[s.layer].push(s);
183
+ }
184
+ // 12. Evidence-Based Confidence Calculation
185
+ let evidencePoints = 0;
186
+ if (classification.technologies.length > 0)
187
+ evidencePoints += 0.35;
188
+ if (classification.capabilities.length > 0)
189
+ evidencePoints += 0.30;
190
+ if (classification.intents.length > 0)
191
+ evidencePoints += 0.15;
192
+ if (classification.domains.length > 0)
193
+ evidencePoints += 0.10;
194
+ if (options.include && options.include.length > 0)
195
+ evidencePoints += 0.10;
196
+ if (options.collection)
197
+ evidencePoints += 0.20;
198
+ // Penalties for ambiguous, noisy, or empty prompts
199
+ if (prompt.trim().length === 0)
200
+ evidencePoints = 0.05;
201
+ else if (skillsList.length === 1 && skillsList[0].name === "verification" && !classification.isTrivial) {
202
+ evidencePoints = Math.min(evidencePoints, 0.30);
203
+ }
204
+ const confidence = Number(Math.min(0.98, Math.max(0.20, evidencePoints)).toFixed(2));
205
+ // 13. Guardrail Warning for Broad Selection
206
+ let warning;
207
+ if (skillsList.length > 8 && !options.collection) {
208
+ warning = "Warning: broad recommendation set; review routing signals.";
209
+ }
210
+ const summary = `Selected ${skillsList.length} skill(s) across ${Object.values(skillsByLayer).filter((l) => l.length > 0).length} layer(s).`;
211
+ return {
212
+ prompt,
213
+ classification,
214
+ skills: skillsList,
215
+ skillsByLayer,
216
+ dropped,
217
+ confidence,
218
+ dryRun: options.dryRun ?? false,
219
+ warning,
220
+ summary
221
+ };
222
+ function selectSkill(name, reasonFallback, score) {
223
+ if (options.exclude && options.exclude.includes(name))
224
+ return;
225
+ const skill = registry.skills[name];
226
+ if (!skill)
227
+ return;
228
+ const scored = scoredSkills.get(name);
229
+ const finalScore = scored ? Math.max(scored.score, score) : score;
230
+ const explanation = generateSkillExplanation(skill, classification, scored?.reasons || [reasonFallback]);
231
+ selectedMap.set(name, {
232
+ name: skill.name,
233
+ layer: skill.layer,
234
+ score: finalScore,
235
+ reason: explanation,
236
+ path: skill.path
237
+ });
238
+ }
239
+ }