managing-path-cleaning-rules
Что он делает
Этот скилл показывает агенту, как настроить правила, которые упорядочивают адреса веб-страниц в PostHog. Он нужен владельцам сайтов, у которых отчеты разбиты на тысячи почти одинаковых ссылок.
Когда использовать
- ✓Когда в веб-аналитике видно много версий одной страницы с разными ID.
- ✓Когда вы хотите объединить похожие адреса, например страницы пользователей, в одну строку.
- ✓Когда вы хотите проверить или изменить правила, которые очищают адреса страниц.
Ссылка на скилл
https://github.com/PostHog/posthog/blob/master/products/web_analytics/skills/managing-path-cleaning-rules/SKILL.mdСкопируйте и вставьте её в ваш ИИ (Claude, ChatGPT или Cursor) с просьбой следовать инструкциям.
Как использовать
Самый простой способ: скопируйте сообщение и вставьте его в свой ИИ. Он прочитает скилл и выполнит инструкции.
Готовое сообщение для вставки
Для Claude Code, Codex или Cursor: запустите в папке проекта, и скилл установится.
Скачайте SKILL.md и положите его в папку скиллов вашего агента.
Пример запроса к вашему ИИ
“В моих отчетах для каждой страницы профиля пользователя отдельная строка. Можешь настроить правила, чтобы все они объединились в одну строку?”
5 новых скиллов в неделю. 1 минута чтения.
Как это работает
Агент смотрит на реальные адреса страниц, чтобы найти изменяющиеся части, например числа или ID. Он пишет шаблон и понятную замену, проверяет его на данных и упорядочивает правила так, чтобы сначала срабатывали конкретные.
Технический текст (оригинальный SKILL.md)
Оригинальный текст автора на английском, прямо с GitHub.
Managing path cleaning rules
Path cleaning rules normalize $pathname and $entry_pathname so that pages
sharing the same template (/users/123/profile, /users/456/profile, …) collapse
into one row (/users/<id>/profile) in Web analytics tiles, Paths insights, and
any HogQL query that calls apply_path_cleaning. They are the right answer when
a breakdown is fragmented across thousands of near-identical URLs.
This skill teaches you how to:
- recognize when path cleaning is the right tool
- inspect real paths to find what needs cleaning
- write
regex+aliasrules in re2 syntax with the project's placeholder convention - test rules before saving them
- order rules so specific patterns aren't swallowed by generic ones
- apply the rules via MCP
Data model
Team.path_cleaning_filters is a JSON list of PathCleaningFilter objects:
{
"regex": "/users/\\d+/profile",
"alias": "/users/<id>/profile",
"order": 0
}
regex— a re2 pattern. No need to escape/. Anchor with^/$when you mean it.alias— the replacement. Default to angle-bracket placeholders (<id>,<slug>,<uuid>,<date>) so the cleaned path stays human-readable. Backreferences to the regex's capture groups also work, but they cost more to evaluate — see the backreference pitfall below before reaching for one.order— integer. Rules apply sequentially inorderascending, each rule's output feeds the next.
Application is replaceRegexpAll(pathname, regex, alias) per rule, chained.
Workflow
1. Confirm path cleaning is the right move
Ask yourself: is the user complaining about cardinality (too many distinct paths
in a chart), or do they want a per-URL drill-down? Path cleaning is for the
former. If they want per-URL data, suggest a property filter on $pathname
instead.
2. Inspect the real paths
Don't guess at patterns — query them. With the execute-sql MCP tool:
SELECT properties.$pathname AS path, count() AS views
FROM events
WHERE event = '$pageview'
AND timestamp > now() - INTERVAL 7 DAY
GROUP BY path
ORDER BY views DESC
LIMIT 200
Scan the result for:
- numeric IDs:
/users/123,/orders/4242 - UUIDs:
/sessions/8f3c1a3b-… - slugs:
/posts/why-i-love-posthog - dates:
/archive/2024-09-12 - locales:
/en-US/,/fr-FR/ - pagination:
?page=3,/page/3/
3. Draft regex + alias
| Pattern | Example match | regex |
alias |
|---|---|---|---|
| Numeric segment | /users/123/profile |
/users/\d+/profile |
/users/<id>/profile |
| UUID v4 | /sessions/8f3c1a3b-… |
/sessions/[0-9a-f-]{36} |
/sessions/<uuid> |
| Slug | /posts/why-posthog |
/posts/[a-z0-9-]+$ |
/posts/<slug> |
| ISO date | /archive/2024-09-12 |
/archive/\d{4}-\d{2}-\d{2} |
/archive/<date> |
| Locale prefix | /en-US/about |
^/[a-z]{2}-[A-Z]{2}/ |
/<locale>/ |
| Trailing query/page | /blog?page=3 |
\?page=\d+$ |
(empty alias drops it) |
Anchoring rules of thumb:
- start the regex with
^only when the segment must be at the beginning of the path - end with
$to keep a generic rule (e.g.\d+$) from matching mid-path segments
4. Test before saving
Three options, pick one:
Settings page tester:
/settings/project#path_cleaninghas a built-in "test path" input that replays the full ordered chain.Project HogQL (via
execute-sql):SELECT replaceRegexpAll('/users/42/profile', '/users/\d+/profile', '/users/<id>/profile')Chain
replaceRegexpAllcalls in the same order the rules will run if you want to verify multi-rule interaction.Built-in AI helper: there is already an
AiRegexHelpermodal accessible from the rule editor (Help me with Regexbutton) that turns natural language into a regex. Suggest it to the user when they say "I don't know regex" — but always validate the output against real paths via the tester.
5. Order rules from most-specific to most-general
Sequential application means a generic rule placed first will swallow everything that should have hit a specific rule.
order=0 /users/me/profile → /users/me/pro
Частые вопросы
Очищенные адреса появляются в моих отчетах?
Да. Очищенная версия показывается в отчетах и запросах, которые используют эти правила.
Как выглядят плейсхолдеры вроде id?
Это понятные метки, например id или slug, которые в очищенном адресе показываются в угловых скобках.
Почему важен порядок правил?
Широкое правило может перекрыть конкретное, поэтому конкретные шаблоны должны идти первыми.
Подробности
Оригинальное описание автора
Inspects URL paths and proposes, tests, orders, and applies project-level path cleaning rules so dynamic segments (numeric IDs, UUIDs, slugs, dates) collapse into readable aliases. Use when the user says "clean the paths", "normalize URLs", "group similar pages", "too many distinct paths", "/users/123 and /users/456 are the same page", "set up path cleaning", or asks why a Web analytics or Paths breakdown is fragmented across thousands of nearly-identical URLs. Covers regex syntax (re2), alias placeholder convention, rule ordering, the test workflow, and applying rules via the path-cleaning-ru
repo: PostHog/posthog
Популярность
- Звёзды на GitHub
- 41k
- Место в рейтинге
- #6976
- Лицензия
- —
- Обновлён
- 02.11.2026
Комментарии
- …
Другие скиллы из этого репозитория
depot-ci
41kПомогает агенту настроить и запускать workflow в Depot CI, альтернативе GitHub Actions, включая перенос существующих workflow и чтение логов запусков.
depot-container-builds
41kПомогает агенту собирать Docker-образы на удалённых сборщиках Depot, включая мультиплатформенные образы, отправку в реестры и исправление ошибок сборки.
depot-github-runners
41kПомогает агенту переносить задачи GitHub Actions на раннеры Depot: выбирать размер и метки раннера и устранять проблемы настройки.
editing-agents-md
41kПомогает агенту решить, нужно ли правило в файле AGENTS.md или CLAUDE.md, и записать его так, чтобы оно работало, не раздувая файл.
Похожие скиллы
gitcrawl
394kПозволяет агенту искать в сохраненном архиве задач и запросов на слияние GitHub, объединять дубликаты и проверять их текущий статус на GitHub.
slacrawl
394kПозволяет агенту искать и считать сообщения в локальном архиве Slack, проверять его свежесть и при необходимости обновлять архив.
goplaces
394kПомогает агенту искать места, получать их подробности и отзывы и определять названия мест через Google Places, с выводом в JSON для скриптов.