Databrain intelligence

From infometa/workbuddyskills · View interactive version

Databrain intelligence is an AI agent skill from the GitHub repository infometa/workbuddyskills. DataBrain intelligence data query assistant. Translates natural language questions into executable BigQuery SQL for the intelligence domain: market data (Sensortower, Alinea Analytics [Steam raw default], MScience, GSD, Ampere, NPD; Gamalytic legacy), streaming data (Streamhatchet), Steam live CCU (

How to use this skill

Skill file

DataBrain Intelligence Text2SQL

Translate natural language questions about game market intelligence into executable BigQuery SQL using the DataLab HTTP API.

Hard Constraints


Core Tools

| Script | Purpose |

|--------|---------|

| scripts/execute_sql.py | Execute read-only SQL, returns results |

| scripts/search_entity.py | Search DataBrain entities by name — games AND companies/developers/publishers (e.g. "SYBO", "miHoYo"). Returns mobile_id / pc_id / combine_id / entity_id depending on entity_type. Faster & more accurate than SQL LIKE. |

| scripts/fetch_steam_ccu.py | Live Steam CCU via Steam Web API (GetNumberOfCurrentPlayers). Resolve combined_id → steam_id via SQL, then HTTP. Pair with warehouse SQL for trends — see CODE4. |

Workflow

Phase 1 — Understand & Load Reference

Always run section 0 first (glossary / genre clarifications) — it applies to every question regardless of domain. Then pick the matching row from sections 1–4 below and load only the referenced file(s); do not pre-load others.

0. Always-first clarifications (load before anything domain-specific)
1. Intelligence metric tables (DAU / revenue / sales / streaming / store rank / KPI / retention)

Start with CODE0 (master index + Cross-source conventions § 8 — the SoT for *_cid family rules). Then load the specific sub-reference:

| Question pattern | Load |

|---|---|

| Mobile DAU / MAU / revenue / downloads for a mobile title | CODE0. Always use _uid tables (game_metric_sensortower_*_uid). Raw tables (game_metric_sensortower_daily/weekly/monthly) are off-limits except for: Top-N MAU cross-game ranking, entity_name LIKE fallback, or region column queries — see CODE6. |

| Mobile retention (D2/D3/D7/D15/D31, cohort / lifetime) for a mobile title | CODE0. Default = monthly cohort + MAU-weighted; legacy lifetime table only when user explicitly asks launch-to-date — see CODE1 (retention_*.sql). |

| Mobile 用户画像 / demographic / 受众 (gender + age distribution) for a mobile title | CODE0 → Table C — Demographics. Table is keyed by raw app_id (resolve via common.unified_ids); pick the canonical store package per platform. Default granularity='all_time' when no period mentioned; 'quarterly' only when user asks a quarter/recent/trend. Age groups are gender-combined and "<25" = 18–24 bucket. |

| 手游 overlap / 受众重叠 / 重叠度 / affinity / 亲和力 / 亲密度 / 共同用户 | CODE0(必须完整加载,不要截断) — 月度粒度;overlap rate + affinity score;key 为 unified_id_app_a × unified_id_app_b;未指定国家默认 market='us';search_entity.py 返回 mobile_id 直接用,无 mobile_id 则告知用户此表仅覆盖手游 |

| PC / Console multi-metric (revenue + DAU + reviews + mentions for the same game) | CODE0. Prefer pconsole_*_cid; raw single-source only for T-0 freshness / unified_id granularity |

| PC / Console enrichment (ranking + wishlists / reviews / revenue for a title list) | CODE0 → "Steam Top Sellers + pconsole enrichment (recommended template)". Default-latest = 30-day window + per-column non-null aggregation; honor user-specified dates exactly (see intelligence-sources.md § 8 for the decision matrix) |

| Serious external revenue / units number (lifetime, YTD, per-country calibrated total) | CODE0. Use game_metric_calibration_lifetime_daily; label the answer "DataBrain Calibration" + surface calibration_method |

| PC single-source Steam (PCU / ACU / DAU / revenue / units / wishlists / followers / upcoming) | CODE0 (schema + pitfalls). When writing SQL, also load CODE1. Default table: intelligence.game_metric_alinea_daily_cid. Alinea is not real-time — live PCU → CODE3 Pattern 8 + spider_steam_* (segment IS NULL). |

| Steam CCU / 在线 / 同时在线 / PCU 实时 (Steam PC) | CODE0. 「现在多少人」 → scripts/fetch_steam_ccu.py; 趋势 / 排行 / 昨日 → CODE2 + execute_sql.py. Default answer: live API CCU + 30d ACU trend (glossary). |

| Storefront chart positions (Top Sellers / Free / Paid / Grossing / Wish-listed / Played, …) | CODE0. Mobile rankings use intelligence.game_metric_rank_mobile; PC/Console rankings use intelligence.game_metric_rank_pconsole_all |

| Deprecated source asked by name (AppAnnie / VG Insights / Newzoo) | CODE0 for migration; never query |

2. Entity / detail tables (game info, company info, IDs, taxonomy)

| Question pattern | Load |

|---|---|

| Cross-table JOIN — need to map unified_id ↔ edition_id ↔ combined_id ↔ app_id | CODE4 |

| Game info by combined_id only (name, genre, steam_id, release_date string, cover) | CODE1 → combined_detail only (Pattern 2) |

| Game info needing edition_id / app_id / F2P / Game Pass / PS Plus | CODE2 → Pattern 2.1 — not columns on combined_detail |

| Company info: headquarters / headcount / funding / IPO / acquisition | CODE0 |

3. Domain-specific data sources (separate from the intelligence-sources tree)

| Question pattern | Load |

|---|---|

| Roblox CCU / rankings / tags | CODE0 |

| Mini games (微信 / 抖音 / Facebook 小游戏榜单) | CODE0 |

| Research reports / platform coverage stats / MobyGames credits | CODE0 — must return URLs, not file paths; see file's MUST-DO block |

| Benchmark / 对标 / 基准 / 行业中位数 / top 1% / top 10% / peer 排名 / live ops 对标 | CODE0 — resolve metric first via execute_sql.py. A+ group discovery → alignment check → downgrade A5/A1 if no match; then Patterns B–E. For distributions/rankings: country_code='global' + ONE platform口径 (user-specified → exact; unspecified → umbrella PC&Console/Mobile) + GROUP BY game_id. 「steam游戏的退款率一般是多少」等问题直接用 benchmark 回答(refund_rate_lifetime/_30d/_14d/_7d/_90d, global+PC&Console) |

4. Cross-source descriptive layer (limits + answer-labelling)

Phase 1.5 — Resolve Entity IDs

If the entity id appears in chat history, use the IDs directly. Do not call search_entity.py — not even to verify.

Only call search_entity.py for entities absent from that block.

When search_entity.py is needed — always prefer the API over SQL LIKE. Faster, more accurate, avoids ambiguous LIKE matches.

# 游戏
python scripts/search_entity.py --name "游戏名" [--type mobile|pc|console]

# 公司 / 开发商 / 发行商(SYBO、miHoYo、Tencent、网易…)
python scripts/search_entity.py --name "SYBO" --type company

# 不确定是游戏还是公司 → 不传 --type,脚本会自动回退 mobile/pc/console/company
python scripts/search_entity.py --name "SYBO"

API ID → Database column mapping:

| API field | entity_type | DB column | Used in tables |

|-----------|-------------|-----------|----------------|

| mobile_id | mobile | id (= unified_id) | *_uid tables (sensortower_daily_uid, sensortower_monthly_uid, etc.) |

| pc_id | pc | edition_id | game_metric_gamalytic_daily (legacy), ampere_daily (raw); also a usable filter on game_metric_alinea_daily_cid (which carries both combined_id and edition_id). NOT for pconsole_*_cid — use combine_id instead. The raw game_metric_alinea_daily is URL-app_id keyed (NOT edition_id); prefer the _cid variant. |

| console_id | console | edition_id | ampere_daily (raw). NOT for pconsole_*_cid — use combine_id |

| combine_id | (any game) | combined_id | All *_cid tables: pconsole_daily_cid / _weekly_cid / _monthly_cid, alinea_daily_cid / _monthly_cid (Steam, new default), ampere_daily_cid, ampere_monthly_cid; also benchmark.benchmark_game_info.combined_id for benchmark queries |

| entity_id | company | uuid (in company_details) / publisher_id or developer_id (in app_detail / combined_detail) | Look up company profile: WHERE cd.uuid = '<entity_id>'. Find company's games: WHERE ad.publisher_id = '<entity_id>' OR ad.developer_id = '<entity_id>'. company_details has NO company_id column — primary key is uuid. |

#1 silent-failure trap: the *_cid family (pconsole_*_cid, ampere_*_cid) has no edition_id / unified_id columns. Using WHERE edition_id = 'e...' or WHERE unified_id = 'u...' returns 0 rows without any error — the agent will wrongly conclude "no data". Always use combined_id (c prefix) for these tables. If search_entity.py only returned pc_id / mobile_id, resolve to combined_id via common.unified_combined_ids first.

Cross-reference mapping table: common.unified_combined_ids links all ID types together:

SELECT app_id, entity_type, unified_id, edition_id, combined_id
FROM common.unified_combined_ids
WHERE combined_id = 'c00001765'  -- or WHERE edition_id = '...' or unified_id = '...'

Fallback: If the API returns no results or the name is too obscure, fall back to SQL LIKE on common.app_detail (games) or common.company_details (companies).

API search quirks:

Phase 2 — SQL Generation

Default: skip the freshness probe and query directly. Most historical periods have complete data.

Only run SELECT MAX(date) when the query returns empty or unexpectedly sparse results — use it reactively to diagnose why data is missing, not preemptively. CURRENT_DATE() and the current month typically have no data yet; if a query on a recent date returns nothing, probe MAX(date) to find the actual latest available date and re-run.

NEVER probe MIN(date) or MAX(date) when the user has specified explicit dates. Query the data directly with those dates.

SQL Security Filter: The server scans the full SQL text including string literals for forbidden keywords (CALL, UPDATE, DROP, GRANT, EXECUTE, etc.) — game names can trigger this (e.g. 'Call of Duty' triggers CALL). NEVER filter by game name string. Always resolve to unified_id via search_entity.py and filter by ID via JOIN common.unified_ids. Store ranking tables have no unified_id column directly — see references/store-rankings.md for the correct JOIN pattern.

Load references/intelligence-sources.md for full table selection rules.

Generic rules (cross-source)

Source-specific patterns and pitfalls have been moved into the respective reference files. Load the relevant reference (see Phase 1 routing) for Sensortower / Alinea / GSD / game-detail / report / etc. patterns. This list only contains rules that apply regardless of source.

Safety & scope

SQL environment & BigQuery idioms

SELECT DATE_TRUNC(date, WEEK(MONDAY)) AS week,
       MAX(alinea_wishlists_total) AS wishlists_total,
       SUM(alinea_wishlists) AS wishlists
FROM intelligence.game_metric_alinea_daily_cid ...
GROUP BY week

Time-axis column: a chart query must contain exactly one time column for the x-axis. Alias it to the canonical granularity key (week, month, date, quarter, year). Do not select a paired boundary column such as week_end or month_end alongside it — the chart renderer classifies every DATE column as a dimension axis and requires each one to be assigned to either the x-axis, a legend, or a filter. A second uncovered DATE column causes the chart to fall back to ECharts with degraded output. The week_end / month_end expressions in the "BigQuery date idioms" section below are for WHERE-clause range filtering only and must not appear in SELECT.

This applies to pie charts too — WHERE date BETWEEN ... AND ... is not enough. You must also SELECT the time column. There are two patterns:

```sql

-- ✓ trend pie: GROUP BY month + dimension

SELECT DATE_TRUNC(date, MONTH) AS month, market, SUM(revenue) AS revenue

FROM <table>

WHERE <id_filter> AND date BETWEEN '<start>' AND '<end>'

GROUP BY month, market

-- ✓ aggregate pie: MAX(date) AS snapshot_date, no GROUP BY on it

SELECT MAX(date) AS snapshot_date, game_name, SUM(revenue) AS revenue

FROM <table>

WHERE <id_filter> AND date BETWEEN '<start>' AND '<end>'

GROUP BY game_name

-- ✗ wrong: no time column at all — data has no interpretable time period

SELECT game_name, SUM(revenue) AS revenue

FROM <table>

WHERE <id_filter> AND date BETWEEN '<start>' AND '<end>'

GROUP BY game_name

```

Fix: split into layers — compute the window function in an inner query, then aggregate in an outer query (or filter with QUALIFY first, then aggregate).

\[

period = total[end\_date] - total[start\_date - 1]

\]

Decide by the user's date intent:

| User asked for | Date filter | Aggregation |

|---|---|---|

| "latest / current / now" (no date specified) | 30-day window: date BETWEEN DATE_SUB(CURRENT_DATE(), INTERVAL 30 DAY) AND CURRENT_DATE() | per-column non-null aggregation |

| A specific date / range ("2026-03-15", "May 2026", "yesterday") | Honor the user's filter exactly | usually no aggregation; if the slice is mostly NULL, report it as a data observation rather than silently widen the window |

| "As of date X" (snapshot semantics) | Optional ±N-day window anchored at X | per-column non-null aggregation |

Default-latest pattern — 30-day window + MAX of non-null (use only when the user didn't specify a date):

```sql

SELECT

combined_id,

MAX(CASE WHEN alinea_wishlists_total IS NOT NULL

THEN alinea_wishlists_total END) AS wishlists_total,

MAX(CASE WHEN alinea_cumulative_revenue IS NOT NULL

THEN alinea_cumulative_revenue END) AS cum_revenue,

MAX(CASE WHEN all_reviews_count IS NOT NULL AND all_reviews_count > 0

THEN all_reviews_count END) AS reviews,

MAX(CASE WHEN meta_score IS NOT NULL AND meta_score > 0

THEN meta_score END) AS meta

FROM intelligence.game_metric_pconsole_daily_cid

WHERE combined_id IN (...)

AND date BETWEEN DATE_SUB(CURRENT_DATE(), INTERVAL 30 DAY)

AND CURRENT_DATE()

GROUP BY combined_id

```

For point-in-time fields (price, scores) prefer MAX_BY to keep the value from the most recent non-null day:

```sql

MAX_BY(alinea_wishlists_total,

CASE WHEN alinea_wishlists_total IS NOT NULL THEN date END)

AS alinea_wishlists_total

```

Full rationale, measured hit-rate delta (3/50 → 48/50 on default-latest), and a ready-to-run enrichment template live in references/store-rankings.md → Steam Top Sellers + pconsole enrichment.

Default assumptions & comparison discipline

Output & annotation rules

Phase 3 — Execute & Fix

Execute:

python scripts/execute_sql.py --sql "<SQL>" [--schema intelligence]
python scripts/execute_sql.py --sql "SELECT ... FROM benchmark.benchmark_detail ..."
# or, for multi-line / complex SQL:
python scripts/execute_sql.py --sql_file query.sql [--schema intelligence]
python scripts/execute_sql.py --sql_file query.sql   # benchmark: no --schema

CRITICAL — --sql flag is MANDATORY. Never omit it.

- Correct: python scripts/execute_sql.py --sql "<your SQL here>"

- Wrong: python scripts/execute_sql.py "<your SQL here>" — SQL as a bare positional argument always fails.

If you see execute_sql.py: error: unrecognized arguments: SELECT ..., the only fix is to prepend --sql. Do NOT modify or simplify the SQL itself.

On error — auto-fix loop (max 3 rounds): Use scripts/sql_fixer.py to generate a targeted repair prompt, send it back to the model, get revised SQL, re-execute. Stop after 3 failures and report the root cause.

For the full Code / Symptom → Cause → Action table (CLI invocation errors, BigQuery error codes 61001-61006, common SQL mistakes like missing GROUP BY, Not found: Table, NULL DAU/revenue interpretation), see the "Common errors" section in CODE3 module docstring (top of the file).


BigQuery SQL Quick Reference

| Operation | Syntax |

|-----------|--------|

| Last N days | DATE_SUB(CURRENT_DATE(), INTERVAL n DAY) |

| Date truncation | DATE_TRUNC(dt, DAY) / DATE_TRUNC(dt, MONTH) |

| Date formatting | FORMAT_DATE('%Y-%m', dt) |

| Date diff | DATE_DIFF(end, start, DAY) |

| Extract year | FORMAT_DATE('%Y', date) — DO NOT use EXTRACT(YEAR FROM date) because date is a column name that clashes with BigQuery's DATE type keyword in this environment, causing cryptic Unrecognized name errors. Always use FORMAT_DATE instead. |

| Conditional | IF(cond, then, else) or CASE WHEN |

| NULL coalesce | IFNULL(x, default) or COALESCE(x, default) |

| Count if | COUNTIF(condition) |

| Approx distinct | APPROX_COUNT_DISTINCT(x) |

| Filter window results | QUALIFY ROW_NUMBER() OVER (...) = 1 |

| Unnest array | UNNEST([val1, val2, ...]) AS alias |

| JSON extract | JSON_EXTRACT_SCALAR(col, '$.key') |

Always required in BigQuery:


SQL Examples

| File | Load when |

|---|---|

| examples/intelligence_queries.sql | Sensortower / cross-source samples |

| examples/alinea_queries.sql | Alinea Steam PCU / revenue / wishlists / upcoming (Patterns 1–6) |

| examples/benchmark/ | Benchmark metric discovery / distribution / top-N / filtered / single-game (Patterns A–E) |

One SQL block per run — execute_sql.py --sql_file reads the whole file; multi-pattern .sql files (e.g. alinea_queries.sql) will fail. Copy one -- Pattern N section and use --sql '…' or sed -n '…p'.


Extra Tools

Use only when reference files are insufficient or table/column identity is uncertain. Always use --game_code databrain.

| Script | Purpose |

|--------|---------|

| scripts/search_entity.py | Preferred — Search games AND companies by name via API; returns mobile_id/pc_id/combine_id (games) or entity_id (companies) |

| scripts/build_report_url.py | Required for report answers — constructs the DataBrain PDF preview URL from a row of t_intelligence_research_report. Handles double URL-encoding. |

| scripts/fetch_tables.py | Search / browse DataLab tables by keyword (--keywords) |

| scripts/fetch_schema.py | Fetch column schema (--table_ids or --keywords + optional --keyword_limit; --format ai for prompt injection) |

| scripts/schema_linker.py | Filter wide tables (>30 cols) to relevant columns |

| scripts/sql_fixer.py | Generate targeted repair prompts for errored SQL |

| scripts/geo.py | Resolve country/region names to standardized query codes. Use --countries (comma-separated) and/or --regions. Example: --countries '越南,巴基斯坦,印度' or --countries 'vn,pk,in'. If mapping fails, fall back to lowercase ISO-2 codes or look up values in common.country_region. |

| scripts/domain_hints.py | Load domain hints (intelligence, game ID) |

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.