Verified SOP & TutorialAudited Score 98/100

The Complete Production SOP: How to Deploy and Run Shapely Vector Geometry & Topological Predicates in Autonomous AI Agents

Production SOP to install and execute Shapely Vector Geometry in Claude Code, Codex, and Cursor. Fix GEOS errors, run STRtree, and repair invalid polygons.

Target Runtimes:codexclaude-codecursorwindsurf
5 min read • Updated for 2026

Technical Overview & Architectural Context

Autonomous coding agents frequently fail at computational geometry when relying purely on probabilistic Python code generation. Without deterministic SOP guardrails, LLMs generate legacy Shapely 1.x syntax (such as iterating over `.geoms` improperly or invoking deprecated unary unions), ignore GEOS topology errors, and construct self-intersecting polygons (e.g., bowtie polygons) that crash downstream pipelines like PostGIS or Fiona. Agents also default to brute-force $O(N \times M)$ spatial joins instead of leveraging vectorized C-backed GEOS indexers. The `shapely-geometric-predicates-union` skill constrains agent decision trees to Shapely 2.0+ best practices. It enforces topology repair using `shapely.make_valid()`, demands vectorized array-compatible predicate functions (`contains`, `intersects`), and mandates spatial indexing through `shapely.STRtree`. This deterministic SOP guarantees that all generated geospatial operations execute with optimal $O(N \log M)$ complexity and return topologically valid 2D geometries within containerized agent runtimes.

Prerequisites & Environment Requirements

Codex Desktop, Claude Code CLI, Cursor, or Windsurf installed with terminal access
Python 3.10+ and GEOS C-library (bundled automatically with Shapely >= 2.0 binary wheels)
Virtual environment with `pip install shapely>=2.0.0 numpy pytest`

Verified Search Intents & Long-Tail Queries Solved

SEO Audit Score: 98/100

This operational tutorial is engineered to provide deterministic solutions for these developer search queries:

#install shapely-geometric-predicates-union in cursor ide#claude code shapely-geometric-predicates-union rules#codex desktop shapely-geometric-predicates-union setup tutorial#how to fix shapely-geometric-predicates-union agent execution error#shapely 2.0 strtree python spatial index agent prompt#shapely make_valid self-intersecting polygon repair codex#deterministic geospatial agent SOP

Step-by-Step Execution Playbook

1

Local Environment Setup & SKILL.md Mounting

Mount the skill manifest into your agent runtime's global or workspace-level instructions directory.

To inject deterministic geospatial boundaries into Codex, Claude Code, Cursor, or Windsurf, mount the SKILL.md into the agent's active configuration path. The agent runtime indexes the YAML frontmatter triggers (`shapely buffer polygon`, `use shapely strtree`) and enforces the four-step execution SOP whenever geometry manipulation tasks are detected.

Terminal Command
mkdir -p .agents/skills/shapely-geometric-predicates-union && curl -fsSL https://askills.dev/api/skills/shapely-geometric-predicates-union/raw -o .agents/skills/shapely-geometric-predicates-union/SKILL.md
.agents/skills/shapely-geometric-predicates-union/SKILL.md
---
name: "shapely-geometric-predicates-union"
description: "Construct, manipulate, and validate planar 2D geometries using high-performance Shapely 2.0."
metadata:
  author: "Shapely"
  version: "1.0.0"
  runtime_compatibility:
    - "codex"
    - "claude-code"
    - "cursor"
    - "windsurf"
triggers:
  - "shapely buffer polygon"
  - "check polygon intersection shapely"
  - "use shapely strtree"
permissions:
  fs_read: true
  fs_write: "workspace"
  shell_exec: false
  net_access: false
---

# Shapely Vector Geometry & Topological Predicates

## Execution SOP & Rules
1. Import primitives: `from shapely.geometry import Point, Polygon, LineString` and top-level functions `import shapely`.
2. Repair topology: Execute `clean_poly = shapely.make_valid(raw_polygon)` before predicate checks.
3. Create spatial index: Use `tree = shapely.STRtree(polygons_list)` for batch spatial searches.
4. Query spatial relationships: Call `matching_indices = tree.query(search_geom, predicate='intersects')` to avoid O(N^2) loops.
Production Pro-Tip

Place the SKILL.md inside `.cursor/rules/` for Cursor IDE or pass it via `--system-prompt` in Claude Code CLI to minimize redundant context injection across multi-turn sessions.

Sandbox Gotcha

Ensure `permissions.fs_write` is limited to `'workspace'`. Never allow autonomous geometry generation agents to write output files directly to OS system directories or root mounts.

2

Environment Secrets & Dependency Validation

Verify Python C-extension bindings and prevent non-deterministic Shapely 1.x installations.

Shapely 2.0 is a complete rewrite using C-based ufuncs. The agent runtime must verify that the underlying GEOS library matches Shapely 2.0+ specifications, preventing execution failures caused by mixing legacy PyGEOS or Shapely 1.8 methods.

Terminal Command
python -c "import shapely; print('Shapely Version:', shapely.__version__); print('GEOS Version:', shapely.geos_version); assert int(shapely.__version__.split('.')[0]) >= 2, 'Shapely 2.0+ required'"
Production Pro-Tip

Do not pass geospatial API credentials (e.g., Mapbox, Planet Labs) in the agent chat prompt. Store them in `.env.local` and configure `.gitignore` to omit geometry cache dumps.

Sandbox Gotcha

Avoid mixing `pip install shapely` and `pip install pygeos` in the same virtualenv; Shapely 2.0 natively integrates PyGEOS ufuncs and conflicts if both are linked.

3

Intent Matching & Trigger Invocation

Trigger the spatial processing SOP using verified, deterministic prompt commands.

Instruct Codex or Claude Code using exact skill triggers such as 'check polygon intersection shapely' or 'use shapely strtree'. The agent matches the trigger against the frontmatter manifest and immediately applies topological validation constraints rather than guessing planar operations.

Production Pro-Tip

Explicitly prompt: 'Apply shapely-geometric-predicates-union SOP and use shapely.STRtree' to bypass the agent's inclination to write nested nested `for poly1 in list: for poly2 in list:` loops.

Sandbox Gotcha

Do not prompt with ambiguous 3D/spherical requests (e.g., 'calculate haversine polygon'). Shapely handles planar Cartesian 2D geometries; project your coordinates via pyproj before feeding them to Shapely.

4

Verification, Linting & Output Quality Gate

Run topological integrity and performance verification scripts before accepting the generated codebase.

Instruct the autonomous agent to generate an isolated unit test validating that all generated geometries are non-empty, simple, and valid according to GEOS rules. This acts as an automated quality gate preventing invalid geometries from slipping into production datasets.

Terminal Command
pytest -q -k "test_geometry_topology"
Production Pro-Tip

Review `git diff` to ensure the agent didn't reintroduce legacy `.buffer(0)` hacks instead of using the standardized `shapely.make_valid()` method.

Sandbox Gotcha

Buffer operations on invalid geometries produce `GEOSException: TopologyException`. Verify that `shapely.make_valid()` is executed prior to buffering.

Real-World Scenario: High-Throughput Facility Exclusion Zone Analysis Using STRtree Indexing

Tested Trigger Prompt (Feed directly into Codex, Claude, or Cursor):

“Write a Python script that takes 50,000 delivery drop-off Points and 1,200 hazard Polygons. Filter out drop-off points located inside any hazard zone or within a 15-meter buffer of hazard perimeters. Use shapely strtree, check polygon intersection shapely, and ensure all input geometries are valid.”

Deterministic Agent Verification Pipeline:
The agent imports Shapely 2.0 primitives and inspects polygon collections, sanitizing invalid inputs with `shapely.make_valid(polygons)`.
The agent expands hazard perimeters deterministically using vectorized buffering: `buffered_hazards = shapely.buffer(clean_hazards, distance=15.0)`.
The agent constructs a spatial index using `tree = shapely.STRtree(buffered_hazards)`.
The agent queries the spatial tree in bulk using `hazard_indices, point_indices = tree.query(points, predicate='intersects')` to obtain indices in $O(N \log M)$ time.
The agent masks out invalid drop-off points using NumPy boolean indexing and outputs the clean coordinate list with an accompanying verification test.

Runtime Troubleshooting & Failure Modes

Error: GEOSException: TopologyException: Input geom 0 is invalid: Self-intersection at or near point [x] [y]

Root Cause: The agent attempted a predicate test (`intersects`, `contains`) or boolean operation (`union`, `difference`) on a Polygon containing self-crossing boundary rings or bow-tie artifacts without validating it first.

Resolution Command / Fix:
clean_geom = shapely.make_valid(raw_geom)
# If MultiPolygon is returned and Polygon is expected:
clean_poly = clean_geom if clean_geom.geom_type == 'Polygon' else clean_geom.geoms[0]
Error: AttributeError: 'STRtree' object has no attribute 'query_geometries'

Root Cause: The agent generated obsolete Shapely 1.8 code. Shapely 2.0 deprecated `STRtree.query_geometries()` in favor of the vectorized `STRtree.query(geometries, predicate=...)` method which returns integer array indices.

Resolution Command / Fix:
# Update to Shapely 2.0 syntax:
tree = shapely.STRtree(geometries_list)
# Returns tuple of (geom_indices, tree_indices) or integer array depending on input shape
intersecting_indices = tree.query(search_polygon, predicate='intersects')

Frequently Asked Questions (Shapely Vector Geometry & Topological Predicates SOP)

Q:Can I use Shapely Vector Geometry & Topological Predicates across Codex, Claude Code, and Cursor simultaneously?

Yes. The skill conforms to the universal SKILL.md specification. You can place the file in your root workspace or global config (`~/.agents/skills/`), and Codex Desktop, Claude Code CLI, Cursor, and Windsurf will parse the YAML triggers and SOP rules natively.

Q:How does Shapely Vector Geometry & Topological Predicates prevent context window overflow during long agent sessions?

Instead of loading hundreds of lines of geometry parsing examples or raw coordinate GeoJSON arrays into the agent prompt, the skill defines precise SOP constraints and function signatures. This enables autonomous agents to write vectorized C-backed GEOS operations without requiring massive conversational demonstrations.

Q:Does this skill require escalated root or container permissions?

No. The skill is audited with a security score of 98/100 and explicitly enforces `permissions.shell_exec: false` and `permissions.net_access: false`. It executes entirely within the local user workspace sandbox and processes geometric computations locally.

Ready to equip your autonomous agent with Shapely Vector Geometry & Topological Predicates?

Copy the complete audited SKILL.md specification or download the 1-click zip bundle directly from our verified registry.

Get 1-Click Install Spec