Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

docs: add sourcemap symbolication skill (#56842)

Catalin Irimie4d54301b797f
diff --git a/products/error_tracking/skills/diagnosing-stacktrace-symbolication/SKILL.md b/products/error_tracking/skills/diagnosing-stacktrace-symbolication/SKILL.md
new file mode 100644
index 000000000000..36206ea80b66
--- /dev/null
+++ b/products/error_tracking/skills/diagnosing-stacktrace-symbolication/SKILL.md
@@ -0,0 +1,149 @@
+---
+name: diagnosing-stacktrace-symbolication
+description: >
+ Help users debug PostHog Error Tracking stack-trace symbolication for any supported platform — JavaScript/TypeScript
+ web, React Native (Hermes), Android (Proguard / R8), or iOS / macOS (dSYM). The PostHog symbol-set lookup flow is
+ universal across platforms; build-tool and artifact details live in per-platform references (JavaScript is fleshed
+ out, others come as we encounter them). Use when stack frames stay minified or obfuscated after symbols are
+ uploaded, PostHog symbol sets show last_used but frames are not readable, chunk IDs or dSYM UUIDs do not match,
+ "Token not found" appears, uploaded source maps / dSYMs / Proguard mappings look empty, or bundler /
+ symbol-upload configuration needs troubleshooting.
+---
+
+# Diagnosing stack-trace symbolication
+
+Symbolication is the cross-platform name for what JavaScript source-map lookup, Hermes function-offset resolution,
+Proguard / R8 demangling, and dSYM address-to-line lookup all do — turn a minified or obfuscated frame back into a
+readable file, function, and line.
+
+Work through the user's build and PostHog symbol sets as one pipeline: build config -> generated symbol artifacts
+(JavaScript source maps, Hermes maps, Proguard mappings, or dSYM bundles) -> uploaded symbol set in PostHog ->
+captured error frame. Most failures become obvious once those four pieces are checked in order.
+
+## Platforms
+
+| Platform | Symbol-data type | Reference |
+| --------------------------- | ---------------- | ------------------------------------------- |
+| JavaScript / TypeScript web | source-and-map | [javascript.md](./references/javascript.md) |
+| React Native (Hermes) | hermes | _coming soon_ |
+| Android (Proguard / R8) | proguard | _coming soon_ |
+| iOS / macOS (dSYM) | apple-dsym | _coming soon_ |
+
+Step 3 of the workflow (symbol-set lookup in PostHog) is identical across platforms — `posthog-cli symbol-sets
+extract` handles all four container types. Steps 1, 2, and the platform-specific failure modes live in the
+per-platform reference.
+
+## Workflow
+
+### Step 1 - Find how symbol data is produced and uploaded
+
+Look at the app repo's build scripts and PostHog upload config. Confirm which PostHog package handles the upload
+(`@posthog/rollup-plugin`, `@posthog/webpack-plugin`, `@posthog/nextjs-config`, `@posthog/nuxt`, or direct
+`posthog-cli`) and which directory or asset it processes. See the platform reference for build-tool-specific
+config inspection.
+
+For debugging, prefer a build where symbol artifacts remain on disk after upload so you can compare local
+artifacts against what PostHog received. JavaScript example with the Vite plugin (the platform reference covers
+the equivalent setting for other build tools):
+
+```ts
+sourcemaps: {
+ enabled: true,
+ deleteAfterUpload: false,
+}
+```
+
+### Step 2 - Build and inspect local artifacts
+
+Run the production build that uploads symbols, then inspect the emitted files locally. The exact files and helper
+invocation differ per platform — see the platform reference for the helper command, expected file shape, and common
+build-time pitfalls (notably empty-mappings false positives that look like upload bugs but are actually bundler
+config issues).
+
+If local artifacts already look wrong, fix the build before debugging the PostHog upload.
+
+### Step 3 - Check symbol sets in PostHog
+
+Look up the symbol set whose `ref` matches the captured frame's `chunk_id` using the dedicated MCP tools — they
+handle auth, project scoping, and pagination automatically:
+
+- `posthog:error-tracking-symbol-sets-list` with `ref=<chunk_id>` returns the matching row.
+- `posthog:error-tracking-symbol-sets-retrieve` with the ID returns the same shape (and confirms permissions).
+- `posthog:error-tracking-symbol-sets-download-retrieve` returns a one-hour presigned URL pointing at the uploaded
+ symbol-data file. Download it immediately; do not echo the URL back unless the user explicitly asks.
+
+If MCP access is not available, the same data is in **Project settings > Error tracking > Symbol sets** in the
+PostHog UI.
+
+Interpret the row:
+
+- `ref` must match the captured frame `chunk_id`.
+- `last_used` updating means PostHog found and loaded that symbol set. It does not guarantee the frame resolved.
+- `has_uploaded_file: false` means the upload did not complete.
+- A non-null `failure_reason` means PostHog could not parse or load the uploaded symbol data.
+
+The downloaded file is a PostHog symbol-data container (compressed Rust-encoded payload), not plain JSON. Extract
+it with `posthog-cli`:
+
+```bash
+posthog-cli symbol-sets extract symbolset.bin -o ./extracted
+# or, without installing globally:
+# npx @posthog/cli symbol-sets extract symbolset.bin -o ./extracted
+# bunx @posthog/cli symbol-sets extract symbolset.bin -o ./extracted
+```
+
+`posthog-cli symbol-sets extract` handles all four symbol-set types (source-and-map, hermes, proguard, dSYM) and
+writes the extracted files into the output directory. Once extracted, summarize using the platform reference's
+helper.
+
+### Step 4 - Compare local, uploaded, and served files
+
+Use the failure location to decide what to compare:
+
+- Local artifact empty and uploaded artifact empty: build tool emitted unusable symbols.
+- Local artifact valid but uploaded artifact empty: upload processing selected or packed the wrong data.
+- Uploaded artifact valid but production stack stays minified or obfuscated: compare deployed binary bytes to the
+ binary that was uploaded with the symbols.
+- `Token not found`: PostHog loaded the symbol data but the captured generated position did not match any token in
+ the uploaded artifact. Usually points to a changed binary after upload, wrong line / column capture (JavaScript)
+ or wrong frame offset (Hermes / dSYM), or a symbol-coverage bug.
+
+### Step 5 - Fix the most likely layer
+
+Platform-neutral fixes:
+
+- Upload symbols after the final build output exists, not before a later step rewrites it.
+- Use the latest PostHog build plugin and `posthog-cli`.
+- Re-upload changed assets intentionally when the same `ref` was previously uploaded with different content.
+- Remove deployment-time transforms (CDN minify, edge rewrites, compression) that change the served binary after
+ upload.
+
+Platform-specific fixes live in the platform reference.
+
+## Captured frame checks
+
+From an affected PostHog error event, collect one minified application frame:
+
+- `filename`
+- `line` or `lineno`
+- `column` or `colno`
+- `function`
+- `chunk_id` (or platform-equivalent symbol-set ref)
+- any `resolve_failure`, especially `Token not found`
+
+The frame `filename` should match the deployed binary URL. The `chunk_id` should match the symbol set `ref`. The
+captured generated position should point into the same binary that was uploaded with the symbol data.
+
+## Failure matrix (cross-platform)
+
+| Evidence | Likely cause | Next check |
+| ------------------------------------------------ | ----------------------------------------------------------------------- | ----------------------------------------------------------------------------- |
+| No `chunk_id` on frames | Chunk ID injection missing or SDK frame parser did not map the filename | Inspect deployed binary and raw frame filenames. |
+| Symbol set row missing | Upload went to another PostHog project/host or skipped this asset | Compare plugin `projectId`, `host`, and `ref`. |
+| `has_uploaded_file: false` | Upload did not finish | Check build logs; compare `posthog-cli` output to the symbol set row. |
+| Non-null `failure_reason` | PostHog could not parse the uploaded symbol data | Download via Step 3 and inspect the extracted contents. |
+| Uploaded artifact valid, deployed binary differs | Deployment/CDN/post-build transform changed the binary after upload | Compare deployed bytes to local build output. |
+| `Token not found` | Captured position has no token in the uploaded symbol data | Verify captured position, deployed binary identity, and symbol-data coverage. |
+
+Platform-specific failure modes (empty `mappings`, missing `sourcesContent`, Hermes function-offset mismatch,
+Proguard class-name drift, dSYM UUID mismatch) live in the platform reference.
diff --git a/products/error_tracking/skills/diagnosing-stacktrace-symbolication/references/javascript.md b/products/error_tracking/skills/diagnosing-stacktrace-symbolication/references/javascript.md
new file mode 100644
index 000000000000..1cb77082c029
--- /dev/null
+++ b/products/error_tracking/skills/diagnosing-stacktrace-symbolication/references/javascript.md
@@ -0,0 +1,168 @@
+# JavaScript / TypeScript symbolication reference
+
+Companion to [../SKILL.md](../SKILL.md) for JavaScript and TypeScript web apps. Covers `@posthog/rollup-plugin`,
+`@posthog/webpack-plugin`, `@posthog/nextjs-config`, `@posthog/nuxt`, and direct `posthog-cli sourcemap` invocations.
+
+## Step 1 — Build config and packages
+
+Show relevant package versions, using the package manager the repo uses:
+
+```bash
+# pnpm
+pnpm list @posthog/rollup-plugin @posthog/webpack-plugin @posthog/nextjs-config @posthog/nuxt @posthog/cli vite rollup webpack next nuxt --depth 8
+
+# npm
+npm ls @posthog/rollup-plugin @posthog/webpack-plugin @posthog/nextjs-config @posthog/nuxt @posthog/cli vite rollup webpack next nuxt
+
+# yarn (classic)
+yarn list --pattern '@posthog/* vite rollup webpack next nuxt' --depth=0
+
+# bun
+bun pm ls | grep -E '@posthog/|^├── (vite|rollup|webpack|next|nuxt)@'
+```
+
+Use non-zero depth — `@posthog/cli` and Rollup are often transitive dependencies of the build plugin or framework.
+
+Inspect the relevant config files:
+
+- Vite/Rollup: `vite.config.*`, `rollup.config.*`
+- Webpack: `webpack.config.*`
+- Next.js: `next.config.*`
+- Nuxt: `nuxt.config.*`
+
+Search for PostHog upload config:
+
+```bash
+rg -n "posthog|sourcemap|sourceMap|deleteAfterUpload|releaseName|releaseVersion|projectId|envId" .
+```
+
+For Vite/Rollup, confirm source map generation is enabled for production builds. Hidden maps are fine for upload:
+
+```ts
+build: {
+ sourcemap: "hidden",
+}
+```
+
+## Step 2 — Local artifacts
+
+List emitted JS and map files:
+
+```bash
+find dist -type f \( -name '*.js' -o -name '*.mjs' -o -name '*.cjs' -o -name '*.map' \) -print
+```
+
+Inspect with the bundled helper. This is the canonical check — it summarizes JS chunk-id markers and source map
+shape (`mappings_length`, `sources_length`, `sources_content_length`, `names_length`):
+
+```bash
+python3 <skill_dir>/scripts/inspect_sourcemaps.py dist
+```
+
+Resolve `scripts/inspect_sourcemaps.py` relative to the skill directory. It accepts files, directories, and globs.
+
+If the helper isn't accessible (CI runner without Python, etc.), a `jq` one-liner gives a coarse summary of one
+source map:
+
+```bash
+jq '{
+ version,
+ file,
+ chunk_id,
+ sourceRoot,
+ mappingsLength: (.mappings | length),
+ sourcesLength: (.sources | length),
+ sourcesContentLength: (.sourcesContent | length),
+ namesLength: (.names | length),
+ firstSources: .sources[0:5]
+}' dist/assets/app.js.map
+```
+
+For a quick sanity grep on whether chunk IDs landed in the JS:
+
+```bash
+rg -n "chunkId=|_posthogChunkIds|sourceMappingURL" dist
+```
+
+Expected local artifact shape:
+
+- JS has a `chunkId` marker and `_posthogChunkIds` registration.
+- JS has `sourceMappingURL` only when maps are intentionally public. Hidden source maps may omit it.
+- Map has non-empty `mappings`.
+- Map has non-empty `sources`.
+- `sourcesContent` is present when source context should appear in PostHog.
+
+## Smoking gun — empty `mappings`
+
+If `inspect_sourcemaps.py` reports `"empty_mappings": true` on a `.map` file (and `sources_length: 0`,
+`names_length: 0`), the bundler emitted a structurally valid but data-less source map. This is the single strongest
+signal that the bug is upstream of PostHog upload — the CLI faithfully uploads whatever is on disk.
+
+For Vite/Rollup this can happen when `config.build.sourcemap` was unset and a Vite-internal plugin
+(`vite:css-post`, `vite:build-import-analysis`) skipped sourcemap generation during `renderChunk` because it reads
+`config.build.sourcemap` directly rather than the Rollup output option. This is reproducible in Vite 7/Rollup builds
+with CSS/IIFE/import-analysis paths. Check the build log for:
+
+```text
+[plugin vite:css-post] Sourcemap is likely to be incorrect: a plugin (vite:css-post) was used to transform files,
+but didn't generate a sourcemap for the transformation
+```
+
+Workaround: set `build.sourcemap: 'hidden'` (or `true`) in `vite.config.*`. Hidden maps still get uploaded but are
+not advertised via `sourceMappingURL` in the served JS.
+
+For other bundlers, the same class of bug shows up when a transform/plugin returns a sourcemap object with empty
+fields instead of `null`. Inspect the local artifact first, before suspecting upload or processing.
+
+## Inspecting an extracted symbol set
+
+After [Step 3](../SKILL.md#step-3---check-symbol-sets-in-posthog) extracts a JS symbol set with
+`posthog-cli symbol-sets extract`, run the helper on the resulting directory:
+
+```bash
+python3 <skill_dir>/scripts/inspect_sourcemaps.py ./extracted
+```
+
+The helper operates on plain `.js` / `.map` files. If you point it at a raw `.bin` container by mistake, it prints
+a redirect error pointing back at `posthog-cli symbol-sets extract`.
+
+## CLI and plugin logging
+
+PostHog build plugins call `posthog-cli sourcemap process`. For direct CLI checks, use environment variables:
+
+```bash
+POSTHOG_CLI_HOST="$POSTHOG_HOST" \
+POSTHOG_CLI_PROJECT_ID="$POSTHOG_PROJECT_ID" \
+POSTHOG_CLI_API_KEY="$POSTHOG_PERSONAL_API_KEY" \
+RUST_LOG=posthog_cli=debug \
+posthog-cli sourcemap process --directory dist --release-name my-app --release-version 0.0.0
+```
+
+For plugin-based builds, set `logLevel: "debug"` inside the same `posthog({ ... })` options object that holds
+`personalApiKey`/`projectId` in `vite.config.*` / `webpack.config.*` / framework wrapper.
+
+Useful log facts:
+
+- which files were processed.
+- which chunk IDs were injected.
+- whether uploads were skipped because content already matched.
+- whether changed content was skipped because forced overwrite was not enabled.
+- whether a source map was missing, empty, or unparsable.
+
+## JS-specific fixes
+
+In addition to the platform-neutral fixes in [SKILL.md Step 5](../SKILL.md#step-5---fix-the-most-likely-layer):
+
+- Enable production source maps in the bundler (`build.sourcemap: true` or `'hidden'` for Vite/Rollup).
+- Move the PostHog plugin later in the plugin order so it sees final emitted JS chunks.
+- Remove post-build minification, CDN rewrites, asset transforms, or compression steps that change JS after upload.
+
+## JS-specific failure rows
+
+Add these to the cross-platform matrix in [SKILL.md](../SKILL.md#failure-matrix-cross-platform):
+
+| Evidence | Likely cause | Next check |
+| ----------------------------------- | --------------------------------------------------------------------------------------------------- | --------------------------------------------------- |
+| Local map has empty `mappings` | Build chain emitted unusable source map (often Vite `build.sourcemap` unset, see smoking gun above) | Check bundler source map settings and plugin order. |
+| Local map valid, uploaded map empty | CLI/plugin processing bug or wrong file selected during upload | Compare helper output before and after upload. |
+| Resolved names but no context | `sourcesContent` missing or source path unavailable | Check `sourcesContent` and source paths in the map. |
diff --git a/products/error_tracking/skills/diagnosing-stacktrace-symbolication/scripts/inspect_sourcemaps.py b/products/error_tracking/skills/diagnosing-stacktrace-symbolication/scripts/inspect_sourcemaps.py
new file mode 100644
index 000000000000..27cad8109304
--- /dev/null
+++ b/products/error_tracking/skills/diagnosing-stacktrace-symbolication/scripts/inspect_sourcemaps.py
@@ -0,0 +1,163 @@
+#!/usr/bin/env python3
+"""Summarize JavaScript source maps and emitted JS chunks for PostHog symbolication debugging.
+
+JavaScript-only. Hermes, Proguard, and dSYM symbolication are handled by other tools — see the
+parent skill (../SKILL.md) and the per-platform references for those.
+
+Operates on plain `.js` / `.map` files only. To inspect a PostHog symbol-data container downloaded
+from the API, extract it first with `posthog-cli symbol-sets extract <file> -o <dir>` (or
+`npx @posthog/cli ...` / `bunx @posthog/cli ...`) and point this script at the resulting directory.
+"""
+
+from __future__ import annotations
+
+import argparse
+import glob
+import json
+import re
+import sys
+from pathlib import Path
+from typing import Any
+
+POSTHOG_SYMBOL_DATA_MAGIC = b"posthog_error_tracking"
+JAVASCRIPT_SUFFIXES = {".js", ".mjs", ".cjs"}
+MAX_INLINE_VALUE_LENGTH = 240
+
+CHUNK_ID_RE = re.compile(r"chunkId=([^\s]+)")
+SOURCE_MAPPING_URL_RE = re.compile(r"sourceMappingURL=([^\s]+)")
+POSTHOG_CHUNK_IDS_RE = re.compile(r"_posthogChunkIds")
+
+
+def summarize_sourcemap_text(text: str) -> dict[str, Any]:
+ try:
+ source_map = json.loads(text)
+ except json.JSONDecodeError as err:
+ return {
+ "kind": "sourcemap",
+ "valid_json": False,
+ "error": str(err),
+ "bytes": len(text.encode("utf-8")),
+ }
+
+ mappings = source_map.get("mappings")
+ sources = source_map.get("sources")
+ sources_content = source_map.get("sourcesContent")
+ names = source_map.get("names")
+ debug_id = source_map.get("debug_id") or source_map.get("debugId")
+
+ return {
+ "kind": "sourcemap",
+ "valid_json": True,
+ "bytes": len(text.encode("utf-8")),
+ "version": source_map.get("version"),
+ "file": source_map.get("file"),
+ "chunk_id": source_map.get("chunk_id") or source_map.get("chunkId") or debug_id,
+ "debug_id": debug_id,
+ "source_root": source_map.get("sourceRoot"),
+ "mappings_length": len(mappings) if isinstance(mappings, str) else None,
+ "sources_length": len(sources) if isinstance(sources, list) else None,
+ "sources_content_length": len(sources_content) if isinstance(sources_content, list) else None,
+ "names_length": len(names) if isinstance(names, list) else None,
+ "first_sources": sources[:5] if isinstance(sources, list) else None,
+ "empty_mappings": not mappings,
+ }
+
+
+def truncate(value: str, limit: int = MAX_INLINE_VALUE_LENGTH) -> str:
+ if len(value) <= limit:
+ return value
+ return value[: limit - 3] + "..."
+
+
+def summarize_js_text(text: str) -> dict[str, Any]:
+ chunk_ids = CHUNK_ID_RE.findall(text)
+ source_mapping_urls = SOURCE_MAPPING_URL_RE.findall(text)
+ return {
+ "kind": "javascript",
+ "bytes": len(text.encode("utf-8")),
+ "chunk_ids": chunk_ids[:10],
+ "chunk_id_count": len(chunk_ids),
+ "has_posthog_chunk_id_map": bool(POSTHOG_CHUNK_IDS_RE.search(text)),
+ "source_mapping_urls": [truncate(url) for url in source_mapping_urls[:10]],
+ "source_mapping_url_count": len(source_mapping_urls),
+ }
+
+
+def inspect_path(path: Path) -> list[dict[str, Any]]:
+ data = path.read_bytes()
+ base: dict[str, Any] = {"path": str(path), "bytes": len(data)}
+
+ if data.startswith(POSTHOG_SYMBOL_DATA_MAGIC):
+ return [
+ {
+ **base,
+ "error": (
+ "PostHog symbol-data container — extract first with "
+ "`posthog-cli symbol-sets extract <file> -o <dir>` "
+ "(or `npx @posthog/cli ...` / `bunx @posthog/cli ...`), "
+ "then re-run this script against the extracted .js / .js.map files."
+ ),
+ }
+ ]
+
+ text = data.decode("utf-8", errors="replace")
+ stripped = text.lstrip()
+ if path.suffix == ".map" or stripped.startswith("{"):
+ return [{**base, **summarize_sourcemap_text(text)}]
+ return [{**base, **summarize_js_text(text)}]
+
+
+def print_json(value: dict[str, Any]) -> None:
+ print(json.dumps(value, sort_keys=True))
+
+
+def is_interesting_path(path: Path) -> bool:
+ return path.suffix == ".map" or path.suffix in JAVASCRIPT_SUFFIXES
+
+
+def expand_input_path(path: Path) -> list[Path]:
+ path_string = str(path)
+ if glob.has_magic(path_string):
+ matches = [Path(match) for match in glob.glob(path_string, recursive=True)]
+ expanded = sorted(match for match in matches if match.is_file() and is_interesting_path(match))
+ return expanded or [path]
+
+ if path.is_dir():
+ return sorted(child for child in path.rglob("*") if child.is_file() and is_interesting_path(child))
+
+ return [path]
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument(
+ "paths",
+ nargs="+",
+ type=Path,
+ help="JS/map files, directories, or globs. Extract symbol-data containers with posthog-cli first.",
+ )
+ parser.add_argument("--pretty", action="store_true", help="Pretty-print JSON output")
+ args = parser.parse_args()
+
+ exit_code = 0
+ paths = [expanded for path in args.paths for expanded in expand_input_path(path)]
+ for path in paths:
+ try:
+ summaries = inspect_path(path)
+ except Exception as err:
+ summaries = [{"path": str(path), "error": str(err)}]
+ exit_code = 1
+
+ for summary in summaries:
+ if "error" in summary:
+ exit_code = 1
+ if args.pretty:
+ print(json.dumps(summary, indent=2, sort_keys=True))
+ else:
+ print_json(summary)
+
+ return exit_code
+
+
+if __name__ == "__main__":
+ sys.exit(main())