From c33e9077402b94891ef1ea98d36c07dedcdc80f8 Mon Sep 17 00:00:00 2001 From: rohan-tessl Date: Thu, 2 Apr 2026 13:30:30 +0530 Subject: [PATCH] feat: improve 5 lowest-scoring skills for GEO-INFER MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Hey @ActiveInferenceInstitute 👋 I ran your skills through `tessl skill review` at work and found some targeted improvements. Here's the full before/after: | Skill | Before | After | Change | |-------|--------|-------|--------| | geo-infer-intra | 61% | 87% | +26% | | geo-infer-metagov | 64% | 90% | +26% | | geo-infer-examples | 66% | 90% | +24% | | geo-infer-ops | 67% | 90% | +23% | | geo-infer-norms | 69% | 90% | +21% | This PR is intentionally scoped to the 5 lowest-scoring skills to keep it reviewable. More skills can be improved in follow-ups or via automated review on future PRs. Changes: - INTRA: structured 5-step workflow, diverse examples, common pitfalls - METAGOV: concrete description, validation checkpoints, 3 examples, best practices - EXAMPLES: actionable description, validation steps, climate example, pitfalls - OPS: geospatial triggers, validation checkpoints, deployment example, error handling - NORMS: natural-language triggers, metric binding validation, 3 examples, error handling Honest disclosure — I work at @tesslio where we build tooling around skills like these. Not a pitch - just saw room for improvement and wanted to contribute. Want to self-improve your skills? Just point your agent (Claude Code, Codex, etc.) at this Tessl guide: https://docs.tessl.io/evaluate/optimize-a-skill-using-best-practices Thanks in advance 🙏 --- GEO-INFER-EXAMPLES/SKILL.md | 96 +++++++++++++++------- GEO-INFER-INTRA/SKILL.md | 137 +++++++++++++++++++++++--------- GEO-INFER-METAGOV/SKILL.md | 154 ++++++++++++++++++++++++++++++++---- GEO-INFER-NORMS/SKILL.md | 152 +++++++++++++++++++++++++++++------ GEO-INFER-OPS/SKILL.md | 75 +++++++++++++++--- 5 files changed, 496 insertions(+), 118 deletions(-) diff --git a/GEO-INFER-EXAMPLES/SKILL.md b/GEO-INFER-EXAMPLES/SKILL.md index 341f3a48..a9a451b9 100644 --- a/GEO-INFER-EXAMPLES/SKILL.md +++ b/GEO-INFER-EXAMPLES/SKILL.md @@ -1,6 +1,6 @@ --- name: geo-infer-examples -description: Working examples and module orchestration patterns. Use when looking for usage examples, cross-module orchestration patterns, end-to-end workflows, or reference implementations of GEO-INFER capabilities. +description: "Provides runnable code examples and module orchestration patterns for the GEO-INFER framework. Use when wiring GEO-INFER modules together for the first time, finding a working agriculture/climate/health/IoT integration pattern, running a cross-module SPACE-MATH-BAYES pipeline, or adapting a reference implementation to a new geospatial domain." prerequisites: required: [] recommended: [] @@ -13,42 +13,50 @@ examples_dir: ../GEO-INFER-EXAMPLES/examples/ ## Instructions -### Core Capabilities - -- **Module orchestrators**: Cross-module workflow examples -- **Domain examples**: Per-domain analysis workflows -- **Active Inference**: End-to-end inference pipeline examples -- **Integration patterns**: How modules connect and compose +### Step 1: Identify the Example Category -### Key Directories +Browse the examples directory to find the pattern that matches your use case: ```text GEO-INFER-EXAMPLES/examples/ -├── module_orchestrator.py # Cross-module coordination -├── spatial_analysis/ # SPACE + MATH examples -├── active_inference/ # ACT + BAYES examples -└── domain/ # Domain-specific examples +├── module_orchestrators/ # Cross-module coordination pipelines +├── getting_started/ # Beginner walkthroughs +├── agriculture_integration/ # AG + SPACE + RISK workflows +├── climate_integration/ # CLIMATE + TIME + MATH workflows +├── health_integration/ # HEALTH + BAYES + SPACE workflows +├── iot_radiation_monitoring/ # IOT + DATA + SPACE real-time pipelines +└── area_study/ # Region-specific analysis patterns ``` -### Orchestrator Example +### Step 2: Run an Example -```python -from geo_infer_examples.module_orchestrator import ModuleOrchestrator +1. Install required modules for the example (check imports at the top of each script): + ```bash + uv pip install -e ./GEO-INFER-SPACE ./GEO-INFER-MATH ./GEO-INFER-BAYES + ``` +2. Verify imports resolve — run `python -c "from geo_infer_space.backends.h3 import H3Backend"` to confirm each module is installed correctly. +3. Execute the example script: + ```bash + uv run python GEO-INFER-EXAMPLES/examples/module_orchestrators/orchestrator_demo.py + ``` +4. Check output for convergence status and iteration count to confirm the pipeline ran end-to-end. -orchestrator = ModuleOrchestrator(modules=["SPACE", "MATH", "BAYES"]) -result = orchestrator.run(data, max_iterations=100) -# Convergence uses numeric relative-change (not placeholder) -``` +### Core Capabilities + +- **Module orchestrators**: Chain SPACE, MATH, BAYES, ACT, and other modules into convergent pipelines +- **Domain examples**: Agriculture risk, climate analysis, health mapping, IoT monitoring +- **Active Inference**: End-to-end inference pipelines using ACT + BAYES with free energy minimization +- **Integration patterns**: How modules connect, compose, and exchange data across the framework ## Examples ```python +# Cross-module pipeline: SPACE → MATH → BAYES from geo_infer_examples.module_orchestrator import ModuleOrchestrator -# Cross-module pipeline: SPACE → MATH → BAYES orchestrator = ModuleOrchestrator(modules=["SPACE", "MATH", "BAYES"]) result = orchestrator.run(data, max_iterations=100) -# Convergence uses numeric relative-change (not placeholder) +# Convergence uses numeric relative-change threshold print(f"Converged in {result.iterations} iterations") ``` @@ -58,26 +66,56 @@ from geo_infer_ag.models.soil_health import SoilHealthModel from geo_infer_risk.core.risk_engine import RiskEngine from geo_infer_space.backends.h3 import H3Backend -# 1. Tessellate farm boundary +# 1. Tessellate farm boundary into H3 cells cells = H3Backend().tessellate(farm_polygon, resolution=9) # 2. Assess soil health per cell soil = SoilHealthModel() health_scores = {cell: soil.assess(cell) for cell in cells} -# 3. Compute risk +# 3. Compute spatially-aware risk map risk = RiskEngine() risk_map = risk.assess(hazard=drought_index, exposure=health_scores) ``` +```python +# Climate integration: temporal trend analysis over spatial grid +from geo_infer_climate.core.trend_analyzer import TrendAnalyzer +from geo_infer_space.backends.h3 import H3Backend +from geo_infer_time.core.temporal_index import TemporalIndex + +# 1. Define spatial extent and time range +cells = H3Backend().tessellate(region_polygon, resolution=7) +time_range = TemporalIndex(start="2020-01", end="2025-12", freq="monthly") + +# 2. Analyze climate trends per cell over time +analyzer = TrendAnalyzer() +trends = { + cell: analyzer.fit(climate_data[cell], time_range) + for cell in cells +} + +# 3. Identify cells with statistically significant warming +hotspots = [cell for cell, t in trends.items() if t.p_value < 0.05] +``` + ## Guidelines -- `module_orchestrator.py` convergence check uses numeric relative-change -- Missing end-to-end Active Inference tutorial (planned for v0.4.0) -- Test: `uv run python -m pytest GEO-INFER-EXAMPLES/tests/ -v` +### Running and Testing Examples + +- Run all example tests: `uv run python -m pytest GEO-INFER-EXAMPLES/tests/ -v` +- Run a specific example category: `uv run python -m pytest GEO-INFER-EXAMPLES/tests/ -k "agriculture" -v` +- Install module dependencies before running — each example's imports indicate which modules are needed. + +### Common Pitfalls + +- **Missing module installs**: Examples import from multiple GEO-INFER modules. Install all referenced modules before running, or you will get `ModuleNotFoundError`. +- **H3 version mismatch**: SPACE examples require `h3>=4.0.0` (use `latlng_to_cell`, not the legacy `geo_to_h3` API). +- **Convergence tuning**: The `ModuleOrchestrator` uses numeric relative-change for convergence checks. Adjust `max_iterations` and tolerance based on data complexity. +- End-to-end Active Inference tutorial is planned for v0.4.0. ### Integrations -- **INTRA** → Documentation hub links to examples -- **All modules** → Examples demonstrate cross-module workflows -- **TEST** → Example code testable as integration tests +- **INTRA** → Documentation hub links to these examples for onboarding +- **All modules** → Examples demonstrate cross-module data flow and composition +- **TEST** → Example scripts are testable as integration tests via the unified test runner diff --git a/GEO-INFER-INTRA/SKILL.md b/GEO-INFER-INTRA/SKILL.md index e68c87c7..4212b9ba 100644 --- a/GEO-INFER-INTRA/SKILL.md +++ b/GEO-INFER-INTRA/SKILL.md @@ -1,6 +1,6 @@ --- name: geo-infer-intra -description: Central documentation hub and cross-module integration guides for GEO-INFER. Use when navigating documentation, finding cross-module integration patterns, understanding data flow architecture, or locating tutorials and API references. +description: "Central documentation hub and cross-module integration layer for GEO-INFER. Use when onboarding new developers to the framework, wiring together multi-module pipelines (e.g. DATA to SPACE to BAYES), resolving import paths across the 44-module monorepo, looking up API signatures for any module, or debugging cross-module data flow issues." prerequisites: required: [] recommended: [] @@ -13,72 +13,131 @@ examples_dir: ../GEO-INFER-EXAMPLES/examples/ ## Instructions -### Core Capabilities +### When to Use This Skill -- **Documentation hub**: Central `docs/` directory with comprehensive guides -- **Integration guides**: Cross-module data flow patterns and examples -- **Architecture docs**: System design diagrams, module dependency graph -- **API reference**: Consolidated API documentation for all 44 modules -- **Tutorials**: Step-by-step workflows spanning multiple modules +Use `geo-infer-intra` when you need to: -### Key Directories +- Onboard to GEO-INFER and understand the module landscape +- Wire data between two or more modules (e.g. DATA -> SPACE -> BAYES) +- Find the correct import path or API signature for any of the 44 modules +- Debug data format mismatches at module boundaries +- Locate tutorials, architecture diagrams, or integration guides -```text -GEO-INFER-INTRA/docs/ -├── guides/ # How-to guides for common workflows -├── tutorials/ # Step-by-step multi-module tutorials -├── integration/ # Cross-module integration patterns -├── architecture/ # System design and data flow diagrams -└── api/ # Consolidated API reference -``` +### Step-by-Step Workflow -### Cross-Module Integration Pattern +1. **Identify the modules involved**: Determine which GEO-INFER modules your task spans. Check `docs/architecture/` for the module dependency graph. +2. **Check integration guides**: Look in `docs/integration/` for an existing pattern matching your module combination. Many common pipelines (SPACE->MATH->BAYES, DATA->AI->AGENT) are already documented. +3. **Verify data contracts**: Each module expects specific input formats. Cross-reference the API docs in `docs/api/` to confirm the output of module A matches the input of module B. +4. **Build the pipeline**: Import from each module's canonical path (`geo_infer_.core.*` for algorithms, `geo_infer_.api.*` for endpoints). +5. **Test the integration**: Run `uv run python -m pytest GEO-INFER-INTRA/tests/ -v` to validate cross-module flows. -```python -# Example: SPACE → MATH → BAYES pipeline -from geo_infer_space.backends.h3 import H3Backend -from geo_infer_math.core.spatial_statistics import MoranI -from geo_infer_bayes.core.bayesian_inference import BayesianModel +### Key Directories -# 1. Index → 2. Analyze → 3. Model -cells = H3Backend().tessellate(region, resolution=7) -autocorrelation = MoranI(values, weights).compute() -posterior = BayesianModel().fit(data) +```text +GEO-INFER-INTRA/ +├── docs/ +│ ├── guides/ # How-to guides for common workflows +│ ├── tutorials/ # Step-by-step multi-module tutorials +│ ├── integration/ # Cross-module integration patterns +│ ├── architecture/ # System design and data flow diagrams +│ └── api/ # Consolidated API reference +├── src/geo_infer_intra/ +│ ├── core/ # Integration logic and orchestration +│ ├── api/ # Internal API interfaces +│ ├── models/ # Shared data models +│ └── utils/ # Cross-module helpers +└── tests/ # Integration tests ``` ## Examples +### Example 1: Multi-Module Geospatial Pipeline + ```python -# Multi-module data flow: DATA → SPACE → MATH → BAYES +# DATA → SPACE → MATH → BAYES: load, index, analyze, model from geo_infer_data.formats.geojson import GeoJSONLoader from geo_infer_space.backends.h3 import H3Backend from geo_infer_math.core.spatial_statistics import MoranI from geo_infer_bayes.core.bayesian_inference import BayesianModel -# 1. Load → 2. Index → 3. Analyze → 4. Model features = GeoJSONLoader().load("observations.geojson") cells = H3Backend().tessellate(features.bounds, resolution=7) autocorrelation = MoranI(values, weights).compute() posterior = BayesianModel().fit(data) ``` +### Example 2: Module Discovery and Health Check + ```python -# Onboarding: discover module capabilities +# Verify which modules are installed and importable import importlib -for module_name in ["math", "space", "bayes", "act", "risk"]: - mod = importlib.import_module(f"geo_infer_{module_name}") - print(f"geo_infer_{module_name}: {mod.__doc__ or 'No docstring'}") + +MODULE_NAMES = ["math", "space", "bayes", "act", "risk", "data", "ai"] +available, missing = [], [] + +for name in MODULE_NAMES: + try: + mod = importlib.import_module(f"geo_infer_{name}") + available.append(name) + except ImportError: + missing.append(name) + +print(f"Available: {available}") +if missing: + print(f"Missing (install with uv): {missing}") +``` + +### Example 3: Cross-Module Error Handling at Boundaries + +```python +# Safely chain SPACE → MATH with boundary validation +from geo_infer_space.backends.h3 import H3Backend +from geo_infer_math.core.spatial_statistics import MoranI + +cells = H3Backend().tessellate(region, resolution=7) + +if not cells or len(cells) == 0: + raise ValueError("Tessellation produced no cells — check region bounds and resolution") + +values = extract_values(cells) # your extraction logic +weights = compute_spatial_weights(cells) + +if values.shape[0] != weights.shape[0]: + raise ValueError( + f"Shape mismatch: {values.shape[0]} values vs {weights.shape[0]} weights. " + "Ensure spatial weights match the cell count from tessellation." + ) + +result = MoranI(values, weights).compute() ``` ## Guidelines -- Start here when onboarding to GEO-INFER -- Each module's README.md and AGENTS.md provide module-level detail -- Each module's SKILL.md provides quick-reference for Claude Code -- Test: `uv run python -m pytest GEO-INFER-INTRA/tests/ -v` +### Getting Started + +- Start here when onboarding to GEO-INFER; this module is the entry point for understanding the framework +- Each module's `SKILL.md` gives a quick-reference; `AGENTS.md` and `README.md` provide deeper module-level detail +- Use the data flow overview: `Data Sources → DATA → SPACE/TIME → MATH/BAYES/ACT → AI/AGENT → Domain Modules → API/APP` + +### Common Pitfalls + +- **Import path casing**: Most modules use lowercase (`geo_infer_math`), but environmental modules currently use mixed-case dirs (`geo_infer_FOREST`, `geo_infer_MARINE`). Check the actual package directory before importing. +- **H3 version**: SPACE and PLACE modules require `h3>=4.0.0`. Use `latlng_to_cell` / `cell_to_latlng`, not the legacy v3 API. +- **Data format mismatches**: When chaining modules, verify that the output format of one module matches the expected input of the next. GeoJSON features, H3 cell arrays, and numpy arrays are the most common interchange formats. +- **Optional dependencies**: Modules use `try/except` imports for optional deps. If a feature silently returns `None`, check whether the underlying package (e.g. `torch`, `geopandas`) is installed. + +### Testing + +```bash +# Run INTRA integration tests +uv run python -m pytest GEO-INFER-INTRA/tests/ -v + +# Run full cross-module test suite +uv run python GEO-INFER-TEST/run_unified_tests.py --category integration +``` ### Integrations -- **EXAMPLES** → Working code examples referenced from docs -- **All modules** → Central hub linking all module documentation -- **TEST** → Documentation-driven testing patterns +- **EXAMPLES** → Working code examples referenced from docs (`../GEO-INFER-EXAMPLES/examples/`) +- **All 44 modules** → Central hub linking documentation, API references, and integration patterns +- **TEST** → Documentation-driven testing patterns and the unified test runner diff --git a/GEO-INFER-METAGOV/SKILL.md b/GEO-INFER-METAGOV/SKILL.md index 9bfdcc19..81625a91 100644 --- a/GEO-INFER-METAGOV/SKILL.md +++ b/GEO-INFER-METAGOV/SKILL.md @@ -1,6 +1,6 @@ --- name: geo-infer-metagov -description: Meta-governance frameworks for geospatial decision-making. Use when implementing polycentric governance, multi-level institutional analysis, stakeholder engagement, conflict resolution, or adaptive governance scenarios for spatial resource management. +description: "Designs governance structures, maps stakeholder relationships, and resolves spatial resource conflicts for geospatial decision-making. Use when planning land use governance across jurisdictions, running multi-stakeholder spatial planning, analyzing institutional arrangements at multiple governance levels, mediating overlapping territorial claims, or setting up adaptive governance triggers for natural resource management." prerequisites: required: - geo-infer-data @@ -16,43 +16,163 @@ examples_dir: ../GEO-INFER-EXAMPLES/examples/ ## Instructions -### Core Capabilities +### Step 1: Set Up Governance Context -- **Polycentric governance**: Multi-center decision structures (Ostrom framework) -- **Multi-level analysis**: Institutional analysis across governance scales -- **Stakeholder management**: Stakeholder mapping, power analysis, engagement tracking -- **Conflict resolution**: Spatial conflict detection, mediation workflows -- **Adaptation**: Adaptive governance, scenario planning, performance monitoring -- **Accountability**: Decision tracking, audit trails, transparency metrics - -### Key Imports +Define the governance scope by initializing the polycentric governance framework with jurisdictional boundaries and decision centers. Every governance workflow starts here. ```python from geo_infer_metagov.core.polycentric import PolycentricGovernance +from geo_infer_metagov.core.multi_level import MultiLevelAnalyzer + +governance = PolycentricGovernance(region="watershed_district_7") +governance.add_decision_center("municipal", level="local", authority=["zoning", "permits"]) +governance.add_decision_center("regional_authority", level="regional", authority=["water_rights", "environmental"]) + +# Validate hierarchy before proceeding -- catches circular authority delegation +governance.validate_hierarchy() +``` + +### Step 2: Map and Analyze Stakeholders + +Register all relevant stakeholders with power and interest scores (0.0-1.0). Build the power-interest matrix to identify engagement priorities. + +```python from geo_infer_metagov.core.stakeholder import StakeholderAnalyzer + +analyzer = StakeholderAnalyzer() +analyzer.register("community_group", power=0.3, interest=0.9) +analyzer.register("government", power=0.8, interest=0.6) +analyzer.register("private_developer", power=0.7, interest=0.8) +matrix = analyzer.build_power_interest_matrix() +strategies = analyzer.recommend_strategies() +# Verify at least 2 stakeholders registered (matrix degenerates with fewer) +assert len(analyzer.get_registered()) >= 2, "Need at least 2 stakeholders for meaningful analysis" +``` + +### Step 3: Detect and Resolve Conflicts + +Run spatial conflict detection across overlapping jurisdictions or competing land-use claims. Use mediation workflows when conflicts are found. + +```python from geo_infer_metagov.core.conflict_resolution import ConflictResolver + +resolver = ConflictResolver(governance_context=governance) +conflicts = resolver.detect_spatial_conflicts(region="watershed_district_7") +for conflict in conflicts: + resolution = resolver.mediate(conflict, stakeholders=analyzer.get_registered()) +``` + +### Step 4: Configure Adaptive Governance and Monitoring + +Set up scenario planning and performance monitoring to enable the governance framework to adapt to changing conditions. + +```python from geo_infer_metagov.core.adaptation import AdaptiveGovernance from geo_infer_metagov.core.accountability import AccountabilityTracker + +adaptive = AdaptiveGovernance(governance) +adaptive.add_scenario("drought", triggers=["rainfall_below_threshold"]) +adaptive.add_scenario("rapid_development", triggers=["permit_rate_above_threshold"]) + +tracker = AccountabilityTracker(governance) +tracker.enable_audit_trail() +tracker.set_transparency_level("public") ``` ## Examples +### Example 1: Stakeholder Power-Interest Analysis + +Map stakeholders for a coastal development project and generate engagement recommendations. + ```python from geo_infer_metagov.core.stakeholder import StakeholderAnalyzer analyzer = StakeholderAnalyzer() -analyzer.register("community_group", power=0.3, interest=0.9) -analyzer.register("government", power=0.8, interest=0.6) +analyzer.register("fishing_cooperative", power=0.2, interest=0.95) +analyzer.register("port_authority", power=0.85, interest=0.7) +analyzer.register("environmental_ngo", power=0.4, interest=0.9) +analyzer.register("tourism_board", power=0.5, interest=0.6) + matrix = analyzer.build_power_interest_matrix() -priority_engagement = analyzer.recommend_strategies() +# Returns quadrant classification: manage_closely, keep_satisfied, keep_informed, monitor +strategies = analyzer.recommend_strategies() +# fishing_cooperative -> keep_informed (low power, high interest) +# port_authority -> manage_closely (high power, high interest) +``` + +### Example 2: Multi-Level Institutional Analysis + +Analyze governance structures across nested jurisdictional levels for a transboundary resource. + +```python +from geo_infer_metagov.core.institutional import InstitutionalAnalysis +from geo_infer_metagov.core.multi_level import MultiLevelAnalyzer + +ia = InstitutionalAnalysis() +ia.define_rules("constitutional", scope="national", rules=["water_framework_directive"]) +ia.define_rules("collective_choice", scope="regional", rules=["basin_management_plan"]) +ia.define_rules("operational", scope="local", rules=["irrigation_schedule", "extraction_limits"]) + +multi = MultiLevelAnalyzer(ia) +gaps = multi.identify_governance_gaps() +# Returns mismatches between levels (e.g., local rules conflicting with regional mandates) +overlaps = multi.find_jurisdictional_overlaps(region="danube_basin") +``` + +### Example 3: Conflict Detection and Adaptive Response + +Detect spatial conflicts in a mixed-use zone and set up adaptive governance triggers. + +```python +from geo_infer_metagov.core.polycentric import PolycentricGovernance +from geo_infer_metagov.core.conflict_resolution import ConflictResolver +from geo_infer_metagov.core.adaptation import AdaptiveGovernance + +governance = PolycentricGovernance(region="mixed_use_zone_12") +governance.add_decision_center("city_planning", level="local", authority=["land_use"]) +governance.add_decision_center("env_agency", level="regional", authority=["habitat_protection"]) + +resolver = ConflictResolver(governance_context=governance) +conflicts = resolver.detect_spatial_conflicts(region="mixed_use_zone_12") + +adaptive = AdaptiveGovernance(governance) +adaptive.add_scenario("habitat_encroachment", triggers=["development_within_buffer_zone"]) +adaptive.enable_auto_escalation(threshold="high_severity") +# When triggered, escalates conflict to regional level for mediation ``` ## Guidelines -- DAO mechanisms in development (Alpha) +### Best Practices + +- **Register all stakeholders before conflict detection**: The `ConflictResolver` uses stakeholder data to weight dispute severity and recommend appropriate mediation paths. Running detection without stakeholders yields generic results. +- **Define governance levels top-down**: Start with constitutional rules, then collective choice, then operational. The `MultiLevelAnalyzer` checks consistency downward through the hierarchy. +- **Enable audit trails early**: Call `tracker.enable_audit_trail()` before any governance decisions are recorded. Retroactive auditing misses decisions made before activation. +- **Use scenario triggers, not polling**: `AdaptiveGovernance` scenarios with defined triggers are more efficient than periodic checks. Triggers integrate with GEO-INFER-IOT sensor data when available. + +### Common Pitfalls + +- **Power/interest values out of range**: `StakeholderAnalyzer.register()` expects values in `[0.0, 1.0]`. Values outside this range raise `ValueError`. Normalize before registering. +- **Circular authority delegation**: When two decision centers delegate authority to each other, `PolycentricGovernance` raises a `GovernanceCycleError`. Check authority chains with `governance.validate_hierarchy()` before running analysis. +- **Missing governance context in resolver**: `ConflictResolver` requires a `governance_context` parameter. Initializing without one defaults to a flat single-level model, which misses cross-jurisdictional conflicts. +- **Stale scenario triggers**: Adaptive governance scenarios must be refreshed when underlying data sources change. Call `adaptive.refresh_triggers()` after updating connected data pipelines. + +### Edge Cases + +- **No conflicts found**: `resolver.detect_spatial_conflicts()` returns an empty list when no overlapping claims exist. Always check `len(conflicts)` before iterating to avoid silent no-ops in reporting pipelines. +- **Single stakeholder**: The power-interest matrix degenerates with fewer than two stakeholders. `recommend_strategies()` returns a warning and defaults to "manage closely" for solo entries. +- **Cross-module governance**: When governance spans multiple GEO-INFER regions, use `PolycentricGovernance.federate()` to link separate governance instances rather than creating one oversized context. ### Integrations -- Integrates with NORMS for normative governance checks -- Integrates with CIV for participatory governance -- Test: `uv run python -m pytest GEO-INFER-METAGOV/tests/ -v` +- Integrates with **GEO-INFER-NORMS** for normative governance rule validation and compliance checks. +- Integrates with **GEO-INFER-CIV** for participatory governance and civic engagement workflows. +- Integrates with **GEO-INFER-IOT** for real-time sensor triggers in adaptive governance scenarios. +- DAO mechanisms are in development (Alpha) — API may change. + +### Testing + +```bash +uv run python -m pytest GEO-INFER-METAGOV/tests/ -v +``` diff --git a/GEO-INFER-NORMS/SKILL.md b/GEO-INFER-NORMS/SKILL.md index b4cb22c7..7aec7501 100644 --- a/GEO-INFER-NORMS/SKILL.md +++ b/GEO-INFER-NORMS/SKILL.md @@ -1,6 +1,6 @@ --- name: geo-infer-norms -description: Normative inference and compliance tracking for geospatial governance. Use when evaluating spatial policy compliance, tracking governance metrics, computing normative content influence (Jaccard similarity), or managing multi-criteria regulatory frameworks. +description: "Normative inference and compliance tracking for geospatial governance. Use when checking if a land parcel complies with zoning regulations, evaluating spatial policy compliance against threshold/range/boolean criteria, comparing policy documents for normative overlap (Jaccard similarity), assessing economic and environmental impact of zoning changes, or tracking multi-criteria regulatory frameworks across jurisdictions." prerequisites: required: - geo-infer-data @@ -15,43 +15,147 @@ examples_dir: ../GEO-INFER-EXAMPLES/examples/ ## Instructions -### Core Capabilities +### Workflow -- **Compliance tracking**: Threshold, range, and boolean evaluation with weighted scoring -- **Normative inference**: Content influence measurement via Jaccard similarity -- **Policy evaluation**: Multi-criteria governance assessment with configurable metrics -- **Regulatory frameworks**: Spatial regulation management, jurisdiction tracking +1. **Define regulations and metrics** -- Create `ComplianceMetric` objects specifying evaluation type (`threshold`, `range`, `boolean`), primary field, and comparison rules +2. **Initialize a tracker** -- Instantiate `ComplianceTracker` with metrics bound to regulation IDs +3. **Validate metric binding** -- Verify each metric's `regulation_id` matches the target regulation; mismatched IDs silently return `compliance_level=0.0` +4. **Evaluate compliance** -- Call `tracker.evaluate_compliance(entity, regulation, data)` which returns a `ComplianceStatus` with weighted compliance level; check `status.metric_results` for per-metric pass/fail detail +5. **Query results** -- Use `get_entity_compliance()` or `get_regulation_compliance()` with explicit `as_of_date` for reproducible point-in-time queries +6. **Analyze impact** -- For policy changes, use `PolicyImpactAnalyzer` with context data to generate economic, social, and environmental impact reports ### Key Imports ```python -from geo_infer_norms.core.compliance_tracking import compliance_tracking -from geo_infer_norms.core.normative_inference import NormativeInference -from geo_infer_norms.models.metrics import Metric, ComplianceResult +from geo_infer_norms.core.compliance_tracking import ComplianceTracker, ComplianceReport +from geo_infer_norms.core.normative_inference import NormativeInference, SocialNormDiffusion +from geo_infer_norms.core.policy_impact import PolicyImpactAnalyzer, RegulatoryImpactAssessment +from geo_infer_norms.core.zoning_analysis import ZoningAnalyzer +from geo_infer_norms.models.compliance_status import ComplianceStatus, ComplianceMetric +from geo_infer_norms.models.regulation import Regulation +from geo_infer_norms.models.legal_entity import LegalEntity ``` ## Examples +### Example 1: Multi-metric compliance evaluation + +```python +from geo_infer_norms.core.compliance_tracking import ComplianceTracker +from geo_infer_norms.models.compliance_status import ComplianceMetric +from geo_infer_norms.models.regulation import Regulation +from geo_infer_norms.models.legal_entity import LegalEntity + +# Define metrics for an air quality regulation +air_metric = ComplianceMetric.create( + name="pm25_level", + description="PM2.5 particulate threshold", + regulation_id="reg-air-001", + evaluation_type="threshold", + primary_field="pm25", + comparison="less_than", + threshold_value=35.0, + weight=2.0, +) +noise_metric = ComplianceMetric.create( + name="noise_db", + description="Acceptable noise range", + regulation_id="reg-air-001", + evaluation_type="range", + primary_field="noise_level", + range_min=0.0, + range_max=70.0, + weight=1.0, +) + +tracker = ComplianceTracker( + name="Environmental Compliance", + compliance_metrics=[air_metric, noise_metric], +) + +# Evaluate -- returns ComplianceStatus with weighted compliance_level +entity = LegalEntity(id="site-42", name="Industrial Site 42") +regulation = Regulation(id="reg-air-001", name="Air Quality Standard") +status = tracker.evaluate_compliance( + entity, regulation, {"pm25": 28.0, "noise_level": 65} +) +print(f"Compliant: {status.is_compliant}, Level: {status.compliance_level:.2f}") +``` + +### Example 2: Bayesian normative inference with spatial constraints + +```python +from geo_infer_norms.core.normative_inference import NormativeInference +from shapely.geometry import Point, Polygon + +engine = NormativeInference() + +# Add a speed-limit norm with a spatial boundary +zone = Polygon([(0, 0), (1, 0), (1, 1), (0, 1)]) +norm_id = engine.add_norm( + name="speed_limit_30", + condition=lambda obs: obs.get("speed", 0) <= 30, + probability=0.95, + spatial_constraint=zone, +) + +# Record observations and infer compliance +engine.add_observation("vehicle-1", "speed", 25, location=Point(0.5, 0.5)) +probability = engine.infer_compliance("vehicle-1", norm_id) +print(f"Compliance probability: {probability:.2f}") + +# Identify violations across all norms below a threshold +violations = engine.identify_norm_violations("vehicle-1", threshold=0.3) +for v in violations: + print(f" Violation: {v['norm_name']} (severity {v['severity']:.2f})") +``` + +### Example 3: Policy impact assessment + ```python -from geo_infer_norms.core.compliance_tracking import compliance_tracking -from geo_infer_norms.models.metrics import Metric - -metrics = [ - Metric(name="air_quality", value=42, threshold=50, type="threshold"), - Metric(name="noise_level", value=65, range=(0, 70), type="range"), - Metric(name="green_space", value=True, type="boolean"), -] -result = compliance_tracking(metrics) -print(f"Overall compliance: {result.score:.1%}") +from geo_infer_norms.core.policy_impact import PolicyImpactAnalyzer + +class ZoningPolicy: + policy_type = "zoning_change" + zoning_details = {"upzoning": True} + +analyzer = PolicyImpactAnalyzer( + policy=ZoningPolicy(), + context_data={ + "economic_data": { + "property_values": {"total_value": 5_000_000}, + "employment": {"total_jobs": 1200}, + } + }, +) +report = analyzer.generate_impact_report() +econ_df = report["economic"] +print(econ_df[["impact_category", "impact_type", "impact_value"]]) ``` ## Guidelines -- Content influence uses Jaccard similarity (real implementation) -- Compliance evaluation handles threshold/range/boolean types correctly +### Error Handling + +- `evaluate_compliance` logs a warning and returns `compliance_level=0.0` when no metrics match the regulation ID -- always bind metrics to the correct `regulation_id` +- `NormativeInference.check_norm_compliance` catches exceptions in user-supplied `condition` callables and returns `(False, 0.0)` -- keep condition functions pure and free of side effects +- Missing `required_fields` in evaluation data cause per-metric failures (logged), not full evaluation failure -- check `metric_results` in the returned `ComplianceStatus` for individual notes + +### Common Pitfalls + +- **Stale `as_of_date`**: `get_entity_compliance()` defaults to `datetime.now()` -- pass an explicit timestamp for reproducible queries +- **Weight normalization**: Overall compliance level is a weighted average across metrics; uneven weights can mask failing metrics that have low weight +- **Spatial constraint ordering**: Norm spatial constraints are checked before the condition callable -- an entity outside the polygon returns `(False, 1.0)` with full certainty, skipping the condition entirely +- **Norm relationships**: `infer_network_compliance` blends direct probability (70%) with relationship influence (30%) -- ensure `add_norm_relationship` uses correct `relationship_type` values (`"supports"` or `"conflicts"`) ### Integrations -- Integrates with METAGOV for governance compliance monitoring -- Integrates with REQ for requirements compliance tracking -- Test: `uv run python -m pytest GEO-INFER-NORMS/tests/ -v` +- **METAGOV**: Governance compliance monitoring -- feed `ComplianceTracker` outputs into METAGOV dashboards +- **REQ**: Requirements compliance tracking -- map requirement IDs to `regulation_id` fields +- **SPACE**: Export compliance to GeoDataFrame via `export_compliance_to_geodataframe()` for spatial overlay analysis + +### Testing + +```bash +uv run python -m pytest GEO-INFER-NORMS/tests/ -v +``` diff --git a/GEO-INFER-OPS/SKILL.md b/GEO-INFER-OPS/SKILL.md index 314804ed..639e4f67 100644 --- a/GEO-INFER-OPS/SKILL.md +++ b/GEO-INFER-OPS/SKILL.md @@ -1,6 +1,6 @@ --- name: geo-infer-ops -description: Operations, monitoring, and observability for geospatial infrastructure. Use when setting up monitoring dashboards, configuring alerts, tracking system health, or managing deployment of spatial services. +description: "Operations, monitoring, and observability for geospatial infrastructure. Use when setting up Prometheus dashboards for tile server or PostGIS latency, configuring alerts on GIS service health, deploying spatial services to Kubernetes, instrumenting H3 indexing or map query performance, or adding structured logging to cross-module geospatial pipelines." prerequisites: required: [] recommended: @@ -17,22 +17,37 @@ examples_dir: ../GEO-INFER-EXAMPLES/examples/ ### Core Capabilities -- **Monitoring**: System health metrics, spatial operation performance -- **Alerting**: Threshold-based and anomaly-based alerts -- **Log aggregation**: Structured log collection and querying -- **Deployment**: Configuration management for spatial services +- **Monitoring**: Prometheus-compatible metrics (counters, gauges, histograms) for spatial operation performance +- **Alerting**: Threshold-based and anomaly-based alert rules with configurable actions +- **Structured logging**: JSON-formatted log collection via `structlog` with correlation IDs +- **Deployment**: Kubernetes-native configuration management, Docker image builds, and rolling updates - **Observability**: Distributed tracing for cross-module operations +- **Caching & backup**: In-memory cache management and scheduled backup orchestration + +### Workflow + +1. **Configure logging** — call `setup_logging()` early to enable structured JSON output before other ops modules initialize. +2. **Register metrics** — use `MonitoringEngine` to define histograms, gauges, and counters for the spatial operations you need to track. +3. **Set alert rules** — attach `AlertManager` rules to registered metrics with conditions and notification actions. +4. **Instrument operations** — wrap spatial calls (tessellation, queries, indexing) with `monitor.timer()` context managers to capture latency. +5. **Verify metrics export** — call `monitor.export_prometheus(port=9090)` and confirm the endpoint is reachable; catch `OSError` if the port is already bound. +6. **Deploy or update** — use `DeploymentManager` to build images, push to a registry, and apply Kubernetes manifests. Always check `build_docker_image()` return value before pushing. +7. **Validate deployment** — verify the Kubernetes deployment status after `apply_manifest()` and log the outcome via structured logging. ### Key Imports ```python -from geo_infer_ops.core.monitoring import MonitoringEngine +from geo_infer_ops.core.monitoring import MonitoringEngine, record_request from geo_infer_ops.core.alerting import AlertManager from geo_infer_ops.core.deployment import DeploymentManager +from geo_infer_ops.core.logging import setup_logging, get_logger +from geo_infer_ops.core.config import get_config ``` ## Examples +### Monitoring spatial operations + ```python from geo_infer_ops.core.monitoring import MonitoringEngine @@ -48,6 +63,8 @@ monitor.gauge("active_queries", value=42) dashboard_url = monitor.export_prometheus(port=9090) ``` +### Configuring alert rules + ```python from geo_infer_ops.core.alerting import AlertManager @@ -58,18 +75,58 @@ alerts.add_rule( condition="p99 > 500", action="notify_slack" ) +alerts.add_rule( + name="error_spike", + metric="http_errors_total", + condition="rate_5m > 10", + action="page_oncall" +) alerts.start_watching() ``` +### Deploying a spatial service + +```python +from geo_infer_ops.core.deployment import DeploymentManager +from geo_infer_ops.core.logging import setup_logging, get_logger + +setup_logging(log_level="INFO", json_format=True) +logger = get_logger(__name__) + +deployer = DeploymentManager(namespace="geo-prod") +if deployer.build_docker_image(tag="geo-infer-api:v2.1.0"): + deployer.push_docker_image(registry="registry.example.com") + deployer.apply_manifest("k8s/api-deployment.yaml") + logger.info("deployment_complete", service="geo-infer-api", version="v2.1.0") +else: + logger.error("deployment_failed", stage="docker_build") +``` + ## Guidelines -- Uses structured logging (JSON format) -- Prometheus-compatible metrics export +### Best Practices + +- Call `setup_logging()` once at startup before creating monitors or deployers — later calls are ignored due to `cache_logger_on_first_use=True`. +- Use `monitor.timer()` context managers rather than manual start/stop timing to guarantee metric recording even on exceptions. +- Keep alert condition strings simple (`p99 > 500`, `rate_5m > 10`). Complex conditions should be split into multiple rules for clarity. +- Always check `build_docker_image()` return value before pushing — a failed build returns `False` rather than raising. - Test: `uv run python -m pytest GEO-INFER-OPS/tests/ -v` +### Error Handling + +- `DeploymentManager` catches `subprocess.CalledProcessError` internally and returns `False` on build/push failures — always check the boolean result. +- Kubernetes operations raise `kubernetes.client.rest.ApiException` on cluster errors — wrap `apply_manifest` calls in try/except when deploying to uncertain environments. +- `MonitoringEngine.export_prometheus()` will fail if the port is already bound — catch `OSError` and retry on an alternate port or log the conflict. + +### Edge Cases + +- Re-registering a metric with the same name but different type raises a `ValueError` — check existing metrics before calling `register_metric()`. +- `setup_logging(json_format=False)` switches to console-rendered output, useful for local development but not suitable for log aggregation pipelines. +- When running outside a Kubernetes cluster, `DeploymentManager.__init__` falls back to `~/.kube/config` — ensure the file exists or handle the `ConfigException`. + ### Integrations -- **API** → Endpoint monitoring and rate limiting +- **API** → Endpoint monitoring via `record_request()` and rate limiting metrics - **AGENT** → Agent telemetry collection and dashboards - **IOT** → Sensor health monitoring and alerts - **LOG** → Logistics operation monitoring