enigma-api-client 0.3.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. enigma_api_client/__init__.py +16 -0
  2. enigma_api_client/client.py +134 -0
  3. enigma_api_client/client_inject_id_and_typename_helper.py +248 -0
  4. enigma_api_client/client_inject_urls_helper.py +26 -0
  5. enigma_api_client/plugins/.DS_Store +0 -0
  6. enigma_api_client/plugins/enigma-api/.claude-plugin/plugin.json +8 -0
  7. enigma_api_client/plugins/enigma-api/README.md +82 -0
  8. enigma_api_client/plugins/enigma-api/harness/conftest.py +42 -0
  9. enigma_api_client/plugins/enigma-api/harness/test_linter.py +863 -0
  10. enigma_api_client/plugins/enigma-api/harness/test_queries.py +143 -0
  11. enigma_api_client/plugins/enigma-api/harness/test_skill_rules.py +351 -0
  12. enigma_api_client/plugins/enigma-api/pyproject.toml +9 -0
  13. enigma_api_client/plugins/enigma-api/scripts/__pycache__/lint_query.cpython-313.pyc +0 -0
  14. enigma_api_client/plugins/enigma-api/scripts/__pycache__/query_validator.cpython-313.pyc +0 -0
  15. enigma_api_client/plugins/enigma-api/scripts/__pycache__/query_validator.cpython-314.pyc +0 -0
  16. enigma_api_client/plugins/enigma-api/scripts/generate_report.py +384 -0
  17. enigma_api_client/plugins/enigma-api/scripts/lint_query.py +712 -0
  18. enigma_api_client/plugins/enigma-api/scripts/query_validator.py +352 -0
  19. enigma_api_client/plugins/enigma-api/skills/enigma-graphql/SKILL.md +620 -0
  20. enigma_api_client/plugins/enigma-api/skills/enigma-graphql/examples/brand/03_brand_profile.md +163 -0
  21. enigma_api_client/plugins/enigma-api/skills/enigma-graphql/examples/brand/13_brand_dump.md +95 -0
  22. enigma_api_client/plugins/enigma-api/skills/enigma-graphql/examples/derived/07_coalesce_ein_formation.md +146 -0
  23. enigma_api_client/plugins/enigma-api/skills/enigma-graphql/examples/discovery/01_coffee_shops_zip.md +287 -0
  24. enigma_api_client/plugins/enigma-api/skills/enigma-graphql/examples/discovery/11_ol_industry_discovery.md +116 -0
  25. enigma_api_client/plugins/enigma-api/skills/enigma-graphql/examples/export/08_segment_export.md +96 -0
  26. enigma_api_client/plugins/enigma-api/skills/enigma-graphql/examples/kyb/02_officers_lookup.md +366 -0
  27. enigma_api_client/plugins/enigma-api/skills/enigma-graphql/examples/kyb/10_kyb_verify.md +176 -0
  28. enigma_api_client/plugins/enigma-api/skills/enigma-graphql/examples/legal_entity/09_legal_entity_profile.md +97 -0
  29. enigma_api_client/plugins/enigma-api/skills/enigma-graphql/examples/locations/05_brand_locations_by_state.md +120 -0
  30. enigma_api_client/plugins/enigma-api/skills/enigma-graphql/examples/person_search/04_find_person_companies.md +160 -0
  31. enigma_api_client/plugins/enigma-api/skills/enigma-graphql/examples/revenue/06_brand_revenue.md +176 -0
  32. enigma_api_client/plugins/enigma-api/skills/enigma-graphql/examples/risk/12_risk_signals.md +118 -0
  33. enigma_api_client/plugins/enigma-api/skills/enigma-graphql/references/card_transactions.md +91 -0
  34. enigma_api_client/plugins/enigma-api/skills/enigma-graphql/references/field_corrections.json +106 -0
  35. enigma_api_client/plugins/enigma-api/skills/enigma-graphql/references/filter_syntax.md +203 -0
  36. enigma_api_client/plugins/enigma-api/skills/enigma-graphql/references/naics_2022_mapping.json +184 -0
  37. enigma_api_client/plugins/enigma-api/skills/enigma-graphql/references/pagination_template.py +115 -0
  38. enigma_api_client/plugins/enigma-api/skills/enigma-graphql/schema.graphql +44971 -0
  39. enigma_api_client/plugins/enigma-api/skills/enigma-graphql/scripts/test_examples.py +1122 -0
  40. enigma_api_client/plugins/enigma-api/skills/enigma-graphql/scripts/validate_query.py +177 -0
  41. enigma_api_client/plugins/enigma-api/test-cases/graphql-test-cases.md +196 -0
  42. enigma_api_client/plugins/enigma-api/tests/accuracy_cases.csv +116 -0
  43. enigma_api_client/plugins/enigma-api/tests/applicability_review.csv +64 -0
  44. enigma_api_client/plugins/enigma-api/tests/parallel-ground-truth.csv +101 -0
  45. enigma_api_client/plugins/enigma-api/tests/run_tests.sh +320 -0
  46. enigma_api_client/plugins/enigma-api/tests/test_cases.yaml +213 -0
  47. enigma_api_client/plugins/enigma-api/tests/validation_cases.csv +101 -0
  48. enigma_api_client/py.typed +0 -0
  49. enigma_api_client/query_router/__init__.py +3 -0
  50. enigma_api_client/query_router/geo.py +121 -0
  51. enigma_api_client/query_router/templates.py +475 -0
  52. enigma_api_client/strategies/__init__.py +16 -0
  53. enigma_api_client/strategies/agent.py +63 -0
  54. enigma_api_client/strategies/base.py +15 -0
  55. enigma_api_client/strategies/generative.py +143 -0
  56. enigma_api_client/strategies/llm_provider.py +137 -0
  57. enigma_api_client/strategies/service.py +103 -0
  58. enigma_api_client/strategies/template.py +189 -0
  59. enigma_api_client-0.3.1.dist-info/METADATA +257 -0
  60. enigma_api_client-0.3.1.dist-info/RECORD +63 -0
  61. enigma_api_client-0.3.1.dist-info/WHEEL +5 -0
  62. enigma_api_client-0.3.1.dist-info/licenses/LICENSE +201 -0
  63. enigma_api_client-0.3.1.dist-info/top_level.txt +5 -0
@@ -0,0 +1,620 @@
1
+ ---
2
+ name: enigma-graphql
3
+ description: Search and discover businesses using the Enigma GraphQL API. Use when the user wants to find/search/discover/list businesses (by name, industry, location, or characteristics), look up a specific company, search for people or business owners, analyze market segments (e.g., "coffee shops in California", "restaurants in New York"), find businesses by criteria (revenue, operating status, has/lacks phone/email, technology used), verify legal entities, check corporate structure, or explore the Enigma business intelligence graph. Handles both entity resolution (known business names like "Starbucks") and semantic discovery (industry/type-based search like "coffee shops" or "auto repair"). This is the primary skill for ALL Enigma business data lookups and market research queries.
4
+ ---
5
+
6
+ # Enigma GraphQL API Skill
7
+
8
+ You are an expert at constructing and executing GraphQL queries against the Enigma business intelligence API.
9
+
10
+ ## API Basics
11
+
12
+ - **Endpoint**: `https://api.enigma.com/graphql`
13
+ - **Auth**: `x-api-key` header — user must have `ENIGMA_API_KEY` set
14
+ - **Method**: POST with `Content-Type: application/json`
15
+ - **Docs**: https://documentation.enigma.com/
16
+ - **Playground**: https://console.enigma.com/explore/graphql
17
+ - **NEVER use curl** — the API key contains characters that break shell argument parsing. Always use Python `urllib`.
18
+ - **ALWAYS use heredoc** — `python3 << 'PYEOF'` (NOT `python3 -c`) to avoid `$` escaping issues.
19
+
20
+ ## Entity Model
21
+
22
+ | EntityType | Description | Key Connections | Scalar Fields |
23
+ |---|---|---|---|
24
+ | `BRAND` | A business brand/company | `operatingLocations`, `legalEntities`, `industries`, `activities`, `cardTransactions` | `names`, `websites`, `revenueQualities`, `isMarketables`, `locationDescriptions` |
25
+ | `OPERATING_LOCATION` | A physical business location | `brands`, `cardTransactions`, `ranks`, `technologiesUseds`, `reviewSummaries` | `names`, `addresses`, `phoneNumbers`, `operatingStatuses`, `websites`, `locationTypes` |
26
+ | `LEGAL_ENTITY` | A registered legal entity | `operatingLocations`, `roles`, `persons`, `registeredEntities`, `isFlaggedByWatchlistEntries`, `appearsOnWatchlistEntries`, `bankruptcies`, `cannabisLicenses`, `negativeNewses` | `names`, `tins`, `addresses`, `types` |
27
+ | `PERSON` | A person (officer, owner, agent) | `legalEntities` (person-type LE nodes) → traverse `roles` → `registrations` → `registeredEntities` to get companies | `names` (firstName, lastName, fullName, dateOfBirth) |
28
+
29
+ ## Choosing the Right Entity Type
30
+
31
+ | User Intent | Start With | Why |
32
+ |---|---|---|
33
+ | "Find info about [company]" | `BRAND` | Top-level business entity |
34
+ | "Find info about [company] — include people, revenue, HQ" | `BRAND` with `name` (+ optional `website`) | See Brand Profile recipe (`examples/brand/03_brand_profile.md`) |
35
+ | "Find locations of [brand] in [state]" | `BRAND` → filter `operatingLocations` | **NEVER** search `OPERATING_LOCATION` by brand name — returns empty |
36
+ | "Find a specific store at [address]" | `OPERATING_LOCATION` | Direct location lookup. **Must include `street1`** |
37
+ | "Revenue for a specific location" | `OPERATING_LOCATION` with street address → `cardTransactions` | Per-location revenue. Do NOT use Brand-level — it includes entire chain |
38
+ | "Revenue for each location of [brand]" | `BRAND` → `operatingLocations` → `cardTransactions` | Per-location without needing addresses |
39
+ | "Monthly/quarterly revenue trends" | `OPERATING_LOCATION` → `cardTransactions` with `period: "1m"` or `"3m"` | Time series data |
40
+ | "Find all [business type] in [area]" | `BRAND` with `prompt` + `conditions` | Discovery — use `prompt` not `name` |
41
+ | "Find all [type] locations in [area] (interactive)" | `OPERATING_LOCATION` with `brands.industries.industryDesc` | Precise industry matching at location level. See `examples/discovery/11_ol_industry_discovery.md` |
42
+ | "Get contacts for [brand]" | `BRAND` → `legalEntities` → `registeredEntities` → `registrations` → `roles` | **NEVER** traverse `roles` on `Brand` or `OperatingLocation` — always use the legal entity path |
43
+ | "Verify a business / check filings" | `LEGAL_ENTITY` | Registrations, officers, TINs, watchlists |
44
+ | "Get formation info for a legal entity" | `LEGAL_ENTITY` with `name` | See `examples/legal_entity/09_legal_entity_profile.md` |
45
+ | "Who owns [business]?" | `BRAND` → `legalEntities` | Corporate structure |
46
+ | "Who are the officers?" | `LEGAL_ENTITY` → `registeredEntities` → `registrations` → `roles` → `legalEntities` | People are on registrations, NOT `LegalEntity.persons` (usually empty) |
47
+ | "Find a person / companies they own" | `PERSON` with `person: { firstName, lastName }` | Person search |
48
+ | "Risk assessment / revenue quality" | `BRAND` with `revenueQualities` + `cardTransactions` | See `examples/risk/12_risk_signals.md` |
49
+ | "Full brand data dump" | `BRAND` comprehensive query | See `examples/brand/13_brand_dump.md` |
50
+ | "How many [businesses] in [area]?" | `aggregate` query with `count(field: ...)` | Much faster than paginating |
51
+ | "Export all [type] in [area]" | `OPERATING_LOCATION` with `output: { filename }` | Bulk export to S3 |
52
+ | "EIN/TIN for this location" | `OPERATING_LOCATION` with `@coalesce` | Resolves EIN via fallback paths |
53
+ | "When was this business formed?" | `OPERATING_LOCATION` with `@coalesce` | Resolves formation year via fallback |
54
+ | "Check compliance / KYB" | `LEGAL_ENTITY` | Watchlist entries, bankruptcies, registrations |
55
+
56
+ ## Franchise & Chain Resolution
57
+
58
+ V2 GraphQL resolves locations to their **parent brand chain**, not individual franchisees.
59
+
60
+ **Example**: Searching `BRAND` for a Days Inn franchisee returns "Days Inn by Wyndham" with $646M revenue across 1,969 locations, not the ~$331K single-location revenue.
61
+
62
+ **How to detect**: Brand result has hundreds/thousands of locations but user asked about one specific business.
63
+
64
+ **How to get single-location data**:
65
+ 1. Search `OPERATING_LOCATION` with name + full address (including `street1`)
66
+ 2. Query that location's `cardTransactions` for per-location revenue
67
+ 3. See `examples/revenue/06_brand_revenue.md` for the correct pattern
68
+
69
+ ## SearchInput
70
+
71
+ ```graphql
72
+ input SearchInput {
73
+ name: String # Entity resolution — match by known business name
74
+ prompt: String # Semantic discovery — match by type/industry (BRAND only)
75
+ entityType: EntityType! # BRAND | OPERATING_LOCATION | LEGAL_ENTITY | PERSON
76
+ address: AddressInput # { street1, city, state (2-letter), postalCode }
77
+ person: PersonInput # For PERSON: { firstName, lastName, dateOfBirth?, address? }
78
+ website: String # Optional: narrow brand matches
79
+ output: OutputInput # { filename } — triggers bulk export (see examples/export/)
80
+ conditions: Conditions # Optional: server-side filtering (filter, limit, orderBy)
81
+ matchThreshold: Float # 0-1, filter by match confidence
82
+ }
83
+ ```
84
+
85
+ **`name` vs `prompt`** — two fundamentally different search modes:
86
+ - **`name`**: Entity resolution. You must know the business name (e.g., `"Starbucks"`, `"Enigma Technologies Inc"`). Works with all entity types.
87
+ - **`prompt`**: Semantic industry discovery. Finds businesses by type/description (e.g., `"coffee shop"`, `"italian restaurant"`, `"auto repair"`). **Only works with `entityType: BRAND`**. Combine with `conditions` for geographic and status filtering.
88
+
89
+ **CRITICAL**: When users ask to discover/find/list businesses by category or industry in an area, ALWAYS use `prompt` — not `name`. Using `name` with a generic term like "coffee" will fail or return irrelevant results.
90
+
91
+ **AGENT BEHAVIOR — street1 check**: When building an `OPERATING_LOCATION` search without a street address, notify the user: *"For reliable results, I recommend including a street address. Without it, the API may return no results. Do you have one?"*
92
+
93
+ ### SearchInput Conditions (for Discovery)
94
+
95
+ When using `prompt`, attach `conditions` directly on the `SearchInput` to filter which brands are returned. This is different from connection-level `conditions` (which filter nested edges like `operatingLocations`).
96
+
97
+ ```json
98
+ {
99
+ "searchInput": {
100
+ "prompt": "coffee shop",
101
+ "entityType": "BRAND",
102
+ "conditions": {
103
+ "filter": {
104
+ "AND": [
105
+ { "IN": ["operatingLocations.addresses.zip", ["12983", "12946"]] },
106
+ { "EQ": ["operatingLocations.operatingStatuses.operatingStatus", "Open"] }
107
+ ]
108
+ },
109
+ "limit": 10
110
+ }
111
+ }
112
+ }
113
+ ```
114
+
115
+ **SearchInput condition field paths for `BRAND`**:
116
+
117
+ | Filter | Field Path |
118
+ |---|---|
119
+ | State | `operatingLocations.addresses.state` |
120
+ | City | `operatingLocations.addresses.city` (UPPERCASE) |
121
+ | Zip code | `operatingLocations.addresses.zip` |
122
+ | Operating status | `operatingLocations.operatingStatuses.operatingStatus` (`Open` / `Closed`) |
123
+ | Industry code (NAICS) | `industries.industryCode` (pair with `industries.industryType` = `naics_2022_code`) |
124
+ | Has phone | `operatingLocations.roles.phoneNumbers` (use `HAS` operator) |
125
+ | Has email | `operatingLocations.roles.emailAddresses` (use `HAS` operator) |
126
+ | Card revenue | `cardTransactions.projectedQuantity` (pair with `period` and `quantityType` filters) |
127
+
128
+ **SearchInput condition field paths for `OPERATING_LOCATION`**:
129
+
130
+ | Filter | Field Path |
131
+ |---|---|
132
+ | State | `addresses.state` |
133
+ | City | `addresses.city` (UPPERCASE) |
134
+ | Zip code | `addresses.zip` |
135
+ | Operating status | `operatingStatuses.operatingStatus` (`Open` / `Closed`) |
136
+ | Industry (Enigma label) | `brands.industries.industryDesc` (pair with `brands.industries.industryType` = `enigma_industry_description`) |
137
+ | Industry (NAICS code) | `brands.industries.industryCode` (pair with `brands.industries.industryType` = `naics_2022_code`) |
138
+
139
+ **Note**: The address field for zip codes is `zip` (NOT `postalCode`). The `postalCode` field only exists on `AddressInput`, not on the `Address` type used in conditions.
140
+
141
+ ## Industry & NAICS Code Mapping
142
+
143
+ Brands in the Enigma API have two types of industry classification on the `industries` connection:
144
+ - **`naics_2022_code`** — official 2022 NAICS code (e.g., `722515` = "Snack and Nonalcoholic Beverage Bars")
145
+ - **`enigma_industry_description`** — Enigma's own semantic label (e.g., "coffee shop")
146
+
147
+ When a user provides an industry description, CRM industry label, or NAICS code as input, use this section to translate it into the correct NAICS 2022 code for `industries.industryCode` filtering.
148
+
149
+ ### Mapping User Input to NAICS Codes
150
+
151
+ **Step 1: Parse input** — the user may provide a descriptive string (e.g., "HVAC"), a NAICS code (e.g., "238220"), or both.
152
+
153
+ **Step 2: Validate codes** — if a NAICS code is provided, confirm it's a valid 2022 code. Old 2017 codes may need remapping.
154
+
155
+ **Step 3: Choose the right granularity**:
156
+ - **2-digit** (Sector): Very broad (e.g., `23` = Construction). Use when the input spans multiple subsectors.
157
+ - **4-digit** (Industry Group): Moderate (e.g., `8111` = Automotive Repair and Maintenance). Use when the input is a broad category within a sector.
158
+ - **6-digit** (National Industry): Specific (e.g., `238220` = Plumbing, Heating, and Air-Conditioning Contractors). Use when the input maps cleanly to a single industry.
159
+ - **Skip 3-digit and 5-digit levels** — they don't align well with Enigma's data.
160
+
161
+ ### Using NAICS Codes in Queries
162
+
163
+ **Filter brands by NAICS code** — use paired conditions on `industries.industryCode` and `industries.industryType`:
164
+
165
+ ```json
166
+ {
167
+ "searchInput": {
168
+ "prompt": "plumber",
169
+ "entityType": "BRAND",
170
+ "conditions": {
171
+ "filter": {
172
+ "AND": [
173
+ { "EQ": ["industries.industryCode", "238220"] },
174
+ { "IN": ["industries.industryType", "naics_2022_code"] },
175
+ { "EQ": ["operatingLocations.addresses.state", "NY"] }
176
+ ]
177
+ },
178
+ "limit": 10
179
+ }
180
+ }
181
+ }
182
+ ```
183
+
184
+ **When to use `prompt` vs NAICS filtering**:
185
+ - **`prompt` alone**: Best for broad semantic discovery where you want the API to interpret intent (e.g., "coffee shop"). May return adjacent industries.
186
+ - **NAICS filter alone**: Best for precise industry segmentation when you know the exact code. Strict match.
187
+ - **`prompt` + NAICS filter**: Most precise — semantic relevance narrowed to a specific NAICS code. Use when the user provides both an industry description and wants tight classification.
188
+
189
+ For the full NAICS reference table, see `references/naics_2022_mapping.json`.
190
+
191
+ ## Pagination
192
+
193
+ All connections use Relay-style cursor pagination. Max page size: `first: 100`.
194
+
195
+ **No `totalCount`**: Connections do NOT support `totalCount`. Requesting it causes HTTP 400. The only way to know the total number of items is to paginate through all pages and count, or use `hasNextPage` to detect whether more exist.
196
+
197
+ Arguments: `first`, `last`, `after`, `before`, `conditions`.
198
+
199
+ ### Cursor Bug
200
+
201
+ The first page query must NOT declare `$cursor` as a variable. Subsequent pages must include it. Using two separate query strings avoids HTTP 400 errors.
202
+
203
+ See `references/pagination_template.py` for the standard pagination implementation (max 3 pages).
204
+
205
+ ## Connection Filtering
206
+
207
+ Connections accept `conditions: { filter: JSON }` for server-side filtering. See `references/filter_syntax.md` for complete filter syntax and examples.
208
+
209
+ **Quick reference**:
210
+ - **Operators**: `EQ`, `NE`, `GT`, `GTE`, `LT`, `LTE`, `IN`, `LIKE`, `ILIKE`, `HAS`, `IS_NULL`, `IS_NOT_NULL`
211
+ - **Combine**: `AND`, `OR`, `NOT`
212
+ - **Syntax**: `{ "OPERATOR": ["field.path", value] }`
213
+ - **`IS_NULL`/`IS_NOT_NULL`** — single-element array (field path only): `{ "IS_NULL": ["platformBrandId"] }`
214
+ - **Field paths**: Use dot notation (e.g., `addresses.state`, `operatingLocations.addresses.zip`)
215
+
216
+ **Important**: Field values are typically UPPERCASE in the Enigma dataset (e.g., `"NY"` not `"ny"`, `"NEW YORK"` not `"New York"`). Use `ILIKE` for case-insensitive matching if unsure.
217
+
218
+ ## Advanced Directives
219
+
220
+ ### `@coalesce` — Return first non-null from multiple paths
221
+
222
+ `_fn @coalesce(refs: [...])` resolves the first non-null value from multiple graph traversal paths. Use with `@skip(if: true)` to declare paths without returning their data.
223
+
224
+ **Rules for `@coalesce`**:
225
+ - The field **must be aliased** (e.g., `legalName: _fn @coalesce(...)`)
226
+ - Array indices in path use `.0.` notation (e.g., `edges.0.node`)
227
+ - The referenced paths **must be declared** in the query body (even if hidden with `@skip(if: true)`)
228
+
229
+ See `examples/derived/07_coalesce_ein_formation.md` for EIN lookup and formation year patterns.
230
+
231
+ ### `@skip` — Conditionally exclude from response
232
+
233
+ Use `@skip(if: true)` to include a field for `@coalesce` reference purposes without including it in the output. Every `@coalesce` block must have corresponding backing fields with `@skip(if: true)`.
234
+
235
+ ## Background Tasks (Large Result Sets)
236
+
237
+ When `output: { filename: "..." }` is provided on `searchInput`, the API triggers a background export. The data response is `null`, but `extensions.backgroundTasks` contains a signed S3 URL to download the full result set.
238
+
239
+ ```json
240
+ {
241
+ "extensions": {
242
+ "backgroundTasks": [
243
+ {
244
+ "id": "uuid",
245
+ "status": "SUCCESS",
246
+ "result": ["https://...s3.amazonaws.com/...signed-url..."]
247
+ }
248
+ ]
249
+ },
250
+ "data": { "search": null }
251
+ }
252
+ ```
253
+
254
+ Use background tasks when a query might return thousands of locations (e.g., all nail salons in a state). The signed URL is valid for ~6 days. Download with `urllib.request.urlretrieve(url, "output.json")`.
255
+
256
+ See `examples/export/08_segment_export.md` for a complete working example.
257
+
258
+ ## Execution Template
259
+
260
+ **Always check for the API key first**, then use this template:
261
+
262
+ ```bash
263
+ python3 << 'PYEOF'
264
+ import json, urllib.request, os
265
+
266
+ query = '''YOUR_QUERY_HERE'''
267
+
268
+ variables = { 'searchInput': { 'name': 'BUSINESS_NAME', 'entityType': 'ENTITY_TYPE' } }
269
+
270
+ payload = json.dumps({'query': query, 'variables': variables})
271
+ req = urllib.request.Request(
272
+ 'https://api.enigma.com/graphql',
273
+ data=payload.encode(),
274
+ headers={'content-type': 'application/json', 'x-api-key': os.environ['ENIGMA_API_KEY']}
275
+ )
276
+ try:
277
+ resp = urllib.request.urlopen(req)
278
+ data = json.loads(resp.read())
279
+ if 'errors' in data:
280
+ for err in data['errors']:
281
+ print(f'GraphQL Error: {err.get("message", err)}')
282
+ else:
283
+ print(json.dumps(data, indent=2))
284
+ except urllib.error.HTTPError as e:
285
+ print(f'HTTP {e.code}: {e.read().decode()}')
286
+ except KeyError:
287
+ print('ERROR: ENIGMA_API_KEY not set. Run: export ENIGMA_API_KEY=your_key')
288
+ PYEOF
289
+ ```
290
+
291
+ ## Query Patterns by Use Case
292
+
293
+ ### Discovery: Find All Businesses of Type X in an Area
294
+
295
+ Use `prompt` for semantic industry discovery. This finds businesses you don't know by name. **Only works with `entityType: BRAND`**.
296
+
297
+ See `examples/discovery/01_coffee_shops_zip.md` for a complete working example.
298
+
299
+ **Key pattern**: Use `prompt` on `SearchInput` with `conditions.filter` to narrow by geography/status:
300
+
301
+ ```json
302
+ {
303
+ "searchInput": {
304
+ "prompt": "coffee shop",
305
+ "entityType": "BRAND",
306
+ "conditions": {
307
+ "filter": {
308
+ "AND": [
309
+ { "IN": ["operatingLocations.addresses.zip", ["12983", "12946"]] },
310
+ { "EQ": ["operatingLocations.operatingStatuses.operatingStatus", "Open"] }
311
+ ]
312
+ },
313
+ "limit": 50
314
+ }
315
+ }
316
+ }
317
+ ```
318
+
319
+ ### Discovery: OPERATING_LOCATION by Industry Label
320
+
321
+ Alternative to BRAND+prompt. Use `OPERATING_LOCATION` with `brands.industries.industryDesc` for **precise** industry label matching.
322
+
323
+ See `examples/discovery/11_ol_industry_discovery.md` for a complete working example.
324
+
325
+ **BRAND+prompt vs OPERATING_LOCATION+industry filter**:
326
+ - Use `BRAND` + `prompt` for semantic discovery (e.g., "trendy coffee shop") — flexible but may include adjacent categories
327
+ - Use `OPERATING_LOCATION` + `brands.industries.industryDesc` for precise category matching when you know the Enigma industry label exactly (e.g., "nail salon", "auto repair")
328
+
329
+ ### KYB: Corporate Structure & Officers
330
+
331
+ Search `BRAND`, traverse to `legalEntities`, then into `registeredEntities → registrations → roles` for officers.
332
+
333
+ See `examples/kyb/02_officers_lookup.md` for a complete working example.
334
+
335
+ **Key pattern**: Officers are on `Registration.roles`, NOT `LegalEntity.persons` (which is usually empty).
336
+
337
+ ### KYB: Full Verification with TINs, Watchlists, Bankruptcies
338
+
339
+ Search `LEGAL_ENTITY` directly for compliance data including TIN validity, watchlist screening, and bankruptcy records.
340
+
341
+ See `examples/kyb/10_kyb_verify.md` for verification queries and registration interpretation guidance.
342
+
343
+ ### Person Search: Find Someone's Companies
344
+
345
+ Use `PERSON` entity type with `person: { firstName, lastName }`, then traverse:
346
+ `Person → legalEntities → roles → registrations → registeredEntities`
347
+
348
+ See `examples/person_search/04_find_person_companies.md` for a complete working example.
349
+
350
+ ### Revenue: Brand-Level Card Transactions
351
+
352
+ Card transactions are available on both `Brand` and `OperatingLocation` entities.
353
+
354
+ **ALWAYS filter `cardTransactions`** — never query unfiltered (returns hundreds of records).
355
+
356
+ **Standard filter** for most recent 12-month aggregate revenue:
357
+
358
+ ```json
359
+ {
360
+ "filter": { "AND": [
361
+ { "EQ": ["period", "12m"] },
362
+ { "EQ": ["quantityType", "card_revenue_amount"] },
363
+ { "EQ": ["rank", 0] },
364
+ { "IS_NULL": ["platformBrandId"] }
365
+ ]}
366
+ }
367
+ ```
368
+
369
+ **CRITICAL**: The `IS_NULL: ["platformBrandId"]` filter is **mandatory** at Brand level. Without it, revenue appears **2x-5x inflated** due to aggregate + per-platform records being summed. At OL level, do NOT use this filter — `platformBrandId` doesn't exist on OL transactions.
370
+
371
+ See `examples/revenue/06_brand_revenue.md` for a complete working example with multiple metrics.
372
+
373
+ ### Locations: Filter by State/City
374
+
375
+ **NEVER search `OPERATING_LOCATION` by brand name** — it returns empty results.
376
+
377
+ Instead: Search `BRAND` by name, then filter `operatingLocations` connection server-side:
378
+
379
+ ```graphql
380
+ operatingLocations(first: 100, conditions: $locConditions) {
381
+ edges { node { ... } }
382
+ }
383
+ ```
384
+
385
+ ```json
386
+ {
387
+ "locConditions": {
388
+ "filter": { "EQ": ["addresses.state", "NY"] }
389
+ }
390
+ }
391
+ ```
392
+
393
+ See `examples/locations/05_brand_locations_by_state.md` for a complete working example.
394
+
395
+ ## Field Name Corrections
396
+
397
+ The GraphQL schema has non-intuitive field names. When you encounter an error, consult `references/field_corrections.json` for the correct field name.
398
+
399
+ **Common mistakes**:
400
+ - `OperatingLocationOperatingStatus.status` → `operatingStatus`
401
+ - `Website.url` → `website`
402
+ - `Website.websiteContent` → `websiteContents(first: N)` — it is a **connection**, not a scalar (use `edges { node { httpStatusCode } }`)
403
+ - `Industry.description` → `industryDesc`
404
+ - `Role.title` → `jobTitle`
405
+ - `BrandCardTransaction.amount` → `projectedQuantity`
406
+ - `ReviewSummary.averageRating` → `reviewScoreAvg`
407
+ - `RegisteredEntity.formationDate` → `formationYear` (Int, NOT Date)
408
+ - `search` result shape — `search` returns a **flat `LIST<SearchUnion>`**, NOT `{ edges { node { ... } } }`. Use inline fragments directly on each list item: `search(searchInput: $s) { ...on Brand { ... } }`
409
+ - Connection `conditions` variable type — declare as `$myConditions: ConnectionConditions`, NOT `Conditions`
410
+
411
+ ## Introspection (Troubleshooting)
412
+
413
+ When a field name causes an error, introspect the type:
414
+
415
+ ```bash
416
+ python3 << 'PYEOF'
417
+ import json, urllib.request, os
418
+ query = '{ __type(name: "TYPE_NAME_HERE") { fields { name type { name kind ofType { name } } } } }'
419
+ payload = json.dumps({'query': query})
420
+ req = urllib.request.Request('https://api.enigma.com/graphql', data=payload.encode(),
421
+ headers={'content-type': 'application/json', 'x-api-key': os.environ['ENIGMA_API_KEY']})
422
+ data = json.loads(urllib.request.urlopen(req).read())
423
+ for f in data['data']['__type']['fields']:
424
+ print(f"{f['name']}: {f['type']['name'] or f['type']['kind']}")
425
+ PYEOF
426
+ ```
427
+
428
+ ## Aggregate Queries (Counts)
429
+
430
+ Use `aggregate` with `count(field: ...)` to get counts without paginating. **Much faster** than fetching all pages.
431
+
432
+ **Accepted `count` fields** (singular): `"brand"`, `"operatingLocation"`, `"legalEntity"`
433
+
434
+ ```graphql
435
+ query Aggregate($searchInput: SearchInput!) {
436
+ aggregate(searchInput: $searchInput) {
437
+ brandsCount: count(field: "brand")
438
+ locationsCount: count(field: "operatingLocation")
439
+ }
440
+ }
441
+ ```
442
+
443
+ `count()` also works on `search` results for brand-level counting. Field names are **plural** here (`"operatingLocations"`, `"legalEntities"`). Use aliases when calling `count()` multiple times.
444
+
445
+ For full examples including filtered counts, see `references/pagination_template.py`.
446
+
447
+ ## Mandatory Guardrails
448
+
449
+ These prevent silent data quality issues. ALWAYS apply when constructing queries.
450
+
451
+ ### 1. platformBrandId IS_NULL Filter (Brand Card Transactions)
452
+
453
+ When querying `cardTransactions` at **Brand level**, ALWAYS include:
454
+ ```json
455
+ { "IS_NULL": ["platformBrandId"] }
456
+ ```
457
+
458
+ Without this, revenue appears **2x-5x inflated** due to aggregate + per-platform records being summed.
459
+
460
+ **At OL level**: Do NOT use this filter — `platformBrandId` doesn't exist on OL transactions.
461
+
462
+ ### 2. Explicit periodEndDate (Multi-Metric Card Transactions)
463
+
464
+ For queries with 2+ card transaction metrics, use explicit `periodEndDate` instead of `rank=0`:
465
+ ```json
466
+ { "EQ": ["periodEndDate", "2024-12-31"] }
467
+ ```
468
+
469
+ This prevents temporal misalignment if data updates between filter construction. Single-metric queries can safely use `rank=0`.
470
+
471
+ ### 3. Temporal Consistency
472
+
473
+ Some `quantityType` values have limited history:
474
+ - **Limited**: `card_not_present_revenue_amount` (1-3 months, Brand-level only)
475
+ - **Full history**: All other metrics
476
+
477
+ Warn users if they request limited-availability metrics for dates >3 months ago.
478
+
479
+ ### 4. BRAND Minimum Fields (Every BRAND Query)
480
+
481
+ Every BRAND result must include these baseline fields even if the prompt doesn't ask for them:
482
+
483
+ - `id`
484
+ - `names { edges { node { name } } }`
485
+ - `websites { edges { node { website domain websiteContents(first:1){ edges { node { httpStatusCode } } } } } }` ← all fields, always
486
+ - Primary phone: `operatingLocations(first: 1, conditions: { filter: { HAS: ["phoneNumbers"] } })` → `phoneNumbers(first: 1)`
487
+ - Primary address: `operatingLocations(first: 1)` → `addresses(first: 1)` with `fullAddress streetAddress1 city state zip`
488
+
489
+ See `examples/brand/03_brand_profile.md` for the complete pattern.
490
+
491
+ ### 5. LEGAL_ENTITY Full Profile Fields
492
+
493
+ When querying `LEGAL_ENTITY`, always include the full attribute set via `registeredEntities`:
494
+ - `name`, `formationYear`, `registeredEntityType`
495
+ - Registration address filtered to `status: "active"` — note: `addressType` is on the **edge**, not the address node
496
+ - Brand linkage via `brands`: names, `websites { edges { node { website domain websiteContents(first:1){ edges { node { httpStatusCode } } } } } }`, HQ address via `operatingLocations` → `addresses` (`streetAddress1`, `streetAddress2`, `city`, `state`, `zip`, `msa`)
497
+
498
+ See `examples/legal_entity/09_legal_entity_profile.md` for the complete query.
499
+
500
+ ### 6. Website Fields — Always Fully Expand
501
+
502
+ Whenever `websites` appears in a query, always request ALL node fields and traverse into `websiteContent`:
503
+
504
+ ```graphql
505
+ websites {
506
+ edges {
507
+ node {
508
+ website
509
+ domain
510
+ websiteContents(first: 1) {
511
+ edges { node { httpStatusCode } }
512
+ }
513
+ }
514
+ }
515
+ }
516
+ ```
517
+
518
+ **Never** return a bare `{ node { website } }` or `{ node { website domain } }` — always include `domain` and traverse `websiteContents(first: 1) { edges { node { httpStatusCode } } }`. Note: `websiteContents` is a **connection**, not a scalar field.
519
+
520
+ ### 7. Operating Locations — 500 Limit Unless Address Specified
521
+
522
+ - **No street, city, or state in the query** → use `first: 500`
523
+ - **Street, city, or state present in the query** → apply those as `conditions` on the `operatingLocations` connection using the appropriate field path (`addresses.street1`, `addresses.city`, `addresses.state`, `addresses.zip`)
524
+
525
+ ```graphql
526
+ # No address specified
527
+ operatingLocations(first: 500) {
528
+ pageInfo { hasNextPage endCursor }
529
+ edges { node { ... } }
530
+ }
531
+
532
+ # Address/city/state specified — filter instead
533
+ operatingLocations(first: 500, conditions: $locConditions) {
534
+ pageInfo { hasNextPage endCursor }
535
+ edges { node { ... } }
536
+ }
537
+ ```
538
+
539
+ See `references/pagination_template.py` for the standard pagination implementation.
540
+
541
+ ### 8. technologiesUseds — Restricted to 8 Payment/Commerce Platforms
542
+
543
+ Only query `technologiesUseds` on `OperatingLocation` when the user **explicitly asks** about one of these supported platforms:
544
+
545
+ | Platform | Category |
546
+ |---|---|
547
+ | Stripe | Payment processor |
548
+ | Toast | Restaurant POS |
549
+ | Square | POS / payment processor |
550
+ | Shopify | E-commerce platform |
551
+ | PayPal | Payment processor |
552
+ | Clover | POS system |
553
+ | Braintree | Payment gateway |
554
+ | Adyen | Payment processor |
555
+
556
+ ## Workflow
557
+
558
+ ```
559
+ Task Progress:
560
+ - [ ] Step 1: Identify search mode (name vs prompt)
561
+ - [ ] Step 2: Choose entity type using the decision matrix
562
+ - [ ] Step 3: If card transactions needed — ask user for periodEndDate
563
+ - [ ] Step 4: Check API key
564
+ - [ ] Step 5: Read the relevant example file and select/compose query
565
+ - [ ] Step 6: Execute via the execution template (NEVER curl, ALWAYS heredoc)
566
+ - [ ] Step 7: Check for errors — look for "errors" key before formatting
567
+ - [ ] Step 8: Format results — tables for lists, structured summaries for singles
568
+ - [ ] Step 9: Paginate if needed (max 3 pages)
569
+ ```
570
+
571
+ ## Formatting & Error Handling
572
+
573
+ **Formatting**:
574
+ - **Lists**: Markdown table. Show "Found X results."
575
+ - **Single entity**: Structured summary with labeled fields.
576
+ - **Empty results**: Suggest alternative entity type or `prompt`-based discovery.
577
+ - **Paginated**: "Showing X of Y+ results. Want me to fetch more?"
578
+
579
+ **Common errors**:
580
+
581
+ | Error | Cause | Fix |
582
+ |---|---|---|
583
+ | HTTP 401 | Bad/missing API key | Check `ENIGMA_API_KEY` |
584
+ | HTTP 400 | Malformed query | Check field names, cursor bug, variables. Do NOT use `totalCount`. |
585
+ | "Cannot query field" | Wrong field name | See `references/field_corrections.json` |
586
+ | Empty results | Wrong entity type or name | Try different entity type per decision matrix |
587
+ | Empty OPERATING_LOCATION results | Missing `street1` | Always include `street1` for OL searches |
588
+ | Null fields | Normal — not all fields populated | Report available data, skip nulls |
589
+
590
+ ## Examples by Use Case
591
+
592
+ Read the relevant example file based on the user's request:
593
+
594
+ | Use Case | Example File |
595
+ |---|---|
596
+ | Find businesses by type/industry (BRAND+prompt) | `examples/discovery/01_coffee_shops_zip.md` |
597
+ | Find locations by industry label (OL+industryDesc) | `examples/discovery/11_ol_industry_discovery.md` |
598
+ | Brand profile, marketing, locations | `examples/brand/03_brand_profile.md` |
599
+ | Comprehensive brand data dump | `examples/brand/13_brand_dump.md` |
600
+ | Person search, brand contacts | `examples/person_search/04_find_person_companies.md` |
601
+ | KYB verification, officers, legal entity | `examples/kyb/02_officers_lookup.md` |
602
+ | KYB full verify (TINs, watchlists, bankruptcies, officers) | `examples/kyb/10_kyb_verify.md` |
603
+ | Legal entity profile (formation, registration) | `examples/legal_entity/09_legal_entity_profile.md` |
604
+ | Operating location profile | `examples/locations/05_brand_locations_by_state.md` |
605
+ | Revenue (brand, OL, per-location, time series) | `examples/revenue/06_brand_revenue.md` |
606
+ | Risk signals (revenue quality, transactions, status) | `examples/risk/12_risk_signals.md` |
607
+ | EIN/TIN lookup, formation year, @coalesce | `examples/derived/07_coalesce_ein_formation.md` |
608
+ | Segment / bulk export to S3 | `examples/export/08_segment_export.md` |
609
+ | Card transaction field reference | `references/card_transactions.md` |
610
+
611
+ ## Additional Resources
612
+
613
+ - **Full Schema**: `schema.graphql` — complete schema definition
614
+ - **Filter syntax**: `references/filter_syntax.md` — complete filter operators and examples
615
+ - **Field corrections**: `references/field_corrections.json` — correct field names for common errors
616
+ - **NAICS codes**: `references/naics_2022_mapping.json` — industry code mappings for discovery queries
617
+ - **Pagination template**: `references/pagination_template.py` — standard pagination implementation
618
+ - **Card transactions**: `references/card_transactions.md` — quantityType values, Brand vs OL differences
619
+ - **Query validator**: `scripts/validate_query.py` — static linter for common mistakes
620
+ - **Training examples**: `examples/` directory — complete working examples across all use cases