Skill: peter-wf/analytics-sdk-setup (version 1.0.0)

--- name: analytics-sdk-setup description: Use this skill whenever a user wants a coding agent to audit, install, reconcile, align, or fix TikTok Pixel and/or Meta Pixel code in a real repo — especially for duplicate init, tracking drift, event mapping, consent/CSP/LDU/privacy gating, or unclear analytics ownership. --- # Analytics SDK Setup Use this skill when the user wants a coding agent to inspect, install, compare, align, reconcile, or fix TikTok Pixel and Meta Pixel tracking in a real codebase. Activate it even when the user does not name this skill directly, as long as the real job is repo-level Pixel debugging or alignment work such as duplicate init, broken page-view behavior, tracking drift, event mapping, consent/CSP review, or source-of-truth cleanup. This skill is for repo-aware coding agents such as Claude Code, Cursor, and similar tools. The agent must inspect the repo, find the shared bootstrap location, avoid duplicate initialization, preserve valid existing integrations, and make privacy/compliance decisions explicit before enabling sensitive tracking. ## Companion prompt If the environment does not load `SKILL.md` directly and instead expects a single prompt block, use: - `agent-system-prompt.md` Use `SKILL.md` as the canonical skill specification and `agent-system-prompt.md` as the compact runtime summary. ## Example usage Use this skill for requests like: - "Compare TikTok and Meta tracking in this repo and tell me where they drift." - "Fix duplicate Pixel initialization and keep TikTok and Meta aligned." - "Add Purchase tracking for TikTok and Meta using the same business moment and shared contract." - "Audit ownership, consent gating, and source of truth for TikTok and Meta events." Do not use this skill when the user only wants a conceptual explanation without repo analysis or implementation. ## Core objective This skill is not only about installing or fixing a single Pixel. Its core objective is to help the agent manage TikTok and Meta as a dual-platform tracking system: - verify per-platform correctness - evaluate cross-platform consistency - identify ownership and source of truth - decide what should be unified - decide what should remain platform-specific TikTok may appear first in examples or references, but the skill scope is not TikTok-only. Any implementation, audit, or repair should consider both platforms when they are in scope. ## REQUIRED FIRST STEP Before doing anything, you MUST: 1. classify execution mode (`Mode A`, `Mode B`, or `Mode C`) 2. output the chosen mode explicitly 3. justify the choice in 1-2 lines DO NOT write any code before this step. ## Quick fix mode If the user request is clearly narrow, such as fixing duplicate initialization or adding one event: - skip full governance analysis - focus on local correctness first - only check cross-platform alignment if the user explicitly mentions both platforms or if the local change would obviously create drift Use quick-fix judgment only when the scope is genuinely narrow and privacy blockers are still resolved. Quick fix mode does not bypass the output contract. Keep required sections for the chosen mode, but you may keep non-critical governance sections brief or mark them as not applicable. ## Thinking steps (MUST follow) 1. What is the user asking? 2. Is the repo available? 3. Are blockers present? 4. Choose execution mode. 5. Then proceed. ## When to activate Activate when the user asks for any of the following: - install or fix TikTok Pixel or Meta Pixel - align, reconcile, or compare TikTok and Meta event tracking - investigate duplicate Pixel initialization, broken page-view behavior, or tracking drift - configure event mapping, parameter mapping, deduplication, or Advanced Matching - review CSP, LDU, consent, or PII-related constraints - audit whether the existing analytics integration is correct - clean up analytics ownership or source of truth in a repo - have a coding agent such as Cursor or Claude Code directly implement or debug Pixel integration - produce a governance or reconciliation recommendation for TikTok and Meta tracking This should still activate when the user never says "analytics-sdk-setup" but clearly needs repo-aware Pixel inspection, repair, or alignment. ## When not to activate Do not activate the full execution flow when the user is only asking for: - conceptual explanation, documentation help, or terminology clarification - high-level theoretical differences between TikTok Pixel and Meta Pixel - marketing strategy discussions that do not involve a codebase - analytics analysis work rather than SDK or Pixel integration and repair If the user only wants explanation, answer directly instead of running this full skill workflow. ## Cross-platform decision frame When TikTok and Meta are both in scope, always evaluate the work through these four lenses: 1. `Per-platform correctness` - Is each platform installed correctly, initialized once, and emitting events at the right business moment? 2. `Cross-platform consistency` - Do both platforms represent the same business action with compatible timing and core semantics? 3. `Ownership and source of truth` - Which file, module, wrapper, provider, or tag manager owns bootstrap, event mapping, privacy gating, and parameter contracts? 4. `Governance over local fixes` - Will a local repair improve the overall dual-platform system, or will it increase drift between TikTok and Meta? When a local fix would make dual-platform governance worse, prefer a plan or governance recommendation over a narrow patch. ## Execution mode decision Before proposing code changes, choose exactly one execution mode. ### Mode A: Direct implementation Use direct implementation only when all of the following are true: - The repo is available and the target app or site is identifiable. - A shared bootstrap location or existing analytics abstraction can be located. - The platform scope is clear: TikTok, Meta, or both. - Pixel ID(s) are already provided or a trustworthy config source already exists in the repo. - The intended environment, domain, page scope, or route scope is clear enough to implement safely. - The requested work is concrete, such as install bootstrap, fix duplicate init, or add a specific event. - No unresolved privacy blocker would force the agent to guess consent, LDU, or PII behavior. ### Mode B: Plan first Use plan-first when the codebase is available but the work is still design-heavy, such as: - The shared render path is not obvious. - The repo contains multiple apps, brands, domains, or possible integration points. - The user wants broad TikTok/Meta event alignment rather than one specific fix. - The agent first needs to map business actions to events before editing code. - The current integration mixes wrappers, providers, inline snippets, or tag-manager ownership that needs review first. - The main task is comparison, governance review, or reconciliation rather than a narrow implementation. You MUST NOT modify code or propose patches in this mode. ### Mode C: Questions first Ask the minimum number of high-impact questions first when any blocker is present, including: - Pixel ID is missing and no reliable config source exists in the repo. - Consent, LDU, or PII / Advanced Matching requirements are unknown and would change implementation behavior. - The target app, environment, route scope, or rollout scope is not clear. - Existing analytics provider or tag-manager ownership is unclear. - The user asks to align events, but the underlying business semantics are still ambiguous. You MUST NOT propose implementation or code in this mode. When in doubt, prefer: 1. audit over implementation, 2. plan over broad refactor, 3. preserving existing privacy behavior over enabling new tracking, 4. minimal bootstrap fixes over speculative event expansion. ## Required inputs and blocking conditions Collect or confirm these inputs before substantial changes. ### Required for direct implementation - Which platforms are in scope: TikTok, Meta, or both - Pixel ID(s) or an existing trusted config source - Target app, domains, pages, or route groups - Target environments: production only, staging too, or all environments - Whether the Pixel loads globally or only on selected pages - Which concrete business events need to be tracked, if the request includes event work ### Blocking conditions Do not directly implement sensitive or ambiguous behavior if any of the following is unresolved: - Whether CSP is enabled and whether tracking changes require CSP updates - Whether consent gating exists or should gate load vs event dispatch - Whether LDU rules apply, and whether they are pixel-wide or event-specific - Whether Advanced Matching / PII is allowed - Whether there is a single shared bootstrap location - Whether an existing GTM / analytics provider / wrapper already owns the integration - Whether TikTok and Meta should share one business-event contract or intentionally diverge for part of the flow If a blocker exists, switch to plan-first or questions-first instead of guessing. ## Safe defaults and conservative behavior When information is incomplete, use these defaults: - Do not invent Pixel IDs, event semantics, consent rules, CSP allowlists, LDU policies, or PII sources. - Do not enable Advanced Matching / PII by default. - Do not enable LDU unless the rule is explicit. - If event scope is unclear, limit the work to bootstrap placement, duplicate audit, or a plan. - If environment scope is unclear, prefer existing env gating in the repo instead of inventing a new policy. - If the repo already has analytics config, privacy utilities, or wrappers, reuse them instead of bypassing them. - If page-view semantics are unclear in an SPA, do not add route-change tracking speculatively. - Keep privacy-sensitive behavior disabled until explicitly approved. - Do not force symmetry when a platform-specific difference is intentional or required. ## Repo inspection workflow Always inspect the existing code before adding or moving SDK code. Follow this order: 1. Identify the target app, site, or package the user actually wants tracked. 2. Determine how pages are produced: shared HTML template, SSR layout, SPA shell, Next.js layout, or existing analytics provider. 3. Locate the best shared bootstrap location. 4. Search for existing TikTok and Meta initialization. 5. Search for existing event dispatch, helper wrappers, route-change hooks, and tag-manager bridges. 6. Identify ownership and source of truth for: - bootstrap placement - event taxonomy - parameter contract - consent or privacy gating - tag-manager vs app-code boundaries 7. Classify the governance state as one of: - `single-platform only` - `dual-platform but ungoverned` - `platform-correct but cross-platform drifted` - `aligned with intentional platform-specific differences` - `privacy/governance blocked` 8. Record engineering tags where relevant, such as: - duplicate initialization - event-only mismatch - privacy / gating mismatch - wrapper conflict - CSP blocked 9. Choose the execution mode again if the repo evidence changes the initial judgment. ## Duplicate detection protocol Before changing anything, inspect both direct calls and wrapped integrations. ### Search for direct init and page-view calls - TikTok bootstrap: `ttq.load(` - TikTok base page view: `ttq.page(` - Meta bootstrap: `fbq('init'` - Meta page view: `fbq('track', 'PageView'` ### Also inspect wrapper-level ownership Check for: - analytics provider components - helper functions that wrap `ttq` or `fbq` - tag-manager bridges - root layout or app-shell script injection helpers - route-change hooks that may duplicate page-view behavior ### Treat these as duplicate-risk scenarios - The same platform is initialized from multiple layouts, templates, or app shells. - Base page-view tracking is emitted both by bootstrap and SPA route hooks without clear intent. - A component-level mount or click handler also initializes the SDK. - Inline snippets coexist with a higher-level provider or GTM-managed integration. ### Consolidation rule If duplicate initialization is found and ownership is clear: 1. Keep one initialization in the best shared location. 2. Remove the other init/load calls. 3. Preserve valid event tracking unless it is also incorrect. 4. Reuse or centralize existing config only when it reduces duplication without creating a broader refactor. If ownership is not clear, do not auto-merge competing integrations. Switch to plan-first or questions-first. ## Implementation workflow Use this workflow only in direct-implementation mode. 1. Keep or create exactly one shared bootstrap location per platform. 2. Prefer an existing global layout, base template, app shell, or analytics provider over scattered snippets. 3. Reuse existing config, environment flags, consent utilities, and privacy wrappers when available. 4. Fix duplicate initialization before expanding event code. 5. Define or preserve a shared business-event contract before mapping into TikTok and Meta specifics. 6. Add or normalize event calls only at the real business success point. 7. Align TikTok and Meta payloads only where the same business action is clearly intended on both platforms. 8. Keep changes minimal, localized, and related only to tracking. 9. Prefer fixing broken event calls over re-installing the SDK. Do not: - initialize inside UI components, click handlers, or repeated page scripts - add a second init/load call just because tracking is broken elsewhere - replace a compliant wrapper with a raw snippet unless clearly necessary - do broad refactors unrelated to tracking - claim that dual-platform governance is complete just because one platform is locally correct For detailed bootstrap placement, event naming, mapping, payload examples, and verification guidance, consult `references/install-and-events.md` before implementing event-related changes. ## Plan-only workflow Use this workflow when the repo is available but implementation should not start yet. Produce a concise implementation-ready report with: - confirmed platform scope - likely shared bootstrap location(s) - current state by platform - governance state - duplicate-init findings - existing privacy / consent / CSP constraints - draft event mapping by business action - exact blockers and the recommended next step Prefer a plan over direct edits when the main task is still architecture, scope selection, event design, or cross-platform governance. ## Ownership and source of truth When TikTok and Meta are both in scope, identify and report: - where bootstrap ownership lives - where event taxonomy is defined - where mapping rules are defined - where privacy gates are enforced - whether GTM, app code, wrappers, or backend logic own different parts of the system If ownership is split, the plan or implementation report should say whether that split is intentional, temporary, or the source of current drift. ## Privacy and compliance guardrails Before enabling sensitive behavior, explicitly inspect privacy constraints. - Reuse the project's existing consent and privacy utilities when they exist. - Do not invent CSP allowlists. - Do not invent LDU logic or region rules. - Do not enable Advanced Matching / PII without explicit approval and a legitimate first-party data source. - Do not bypass existing legal, consent, or regional review flows. - If the implementation would change sensitive behavior and the policy is unclear, stop and ask. - If TikTok and Meta are both in scope, review whether the same shared privacy policy should control both platforms. For CSP, consent gating, LDU, identifier handling, and shared privacy governance details, consult `references/privacy-and-csp.md` before implementing those changes. ## Output contract Use one of the following result structures. ### If you are in questions-first mode ```markdown # Analytics SDK questions ## What blocks implementation - ... ## Decisions that affect both TikTok and Meta - ... ## Required answers 1. ... 2. ... 3. ... ## Safe progress so far - ... ``` Ask the minimum number of high-impact questions. Do not dump the full input checklist if only 2-3 answers are blocking progress. ### If you are in plan-first mode ```markdown # Analytics SDK setup plan ## What I confirmed - Platforms: - Framework / render path: - Intended environments: - Tracking scope: - Current state by platform: - Governance state: ## TikTok vs Meta gaps - ... ## What to unify - ... ## What remains platform-specific - ... ## Ownership / source of truth - ... ## Blockers or missing decisions - Pixel ID(s): - CSP status: - Consent gating: - LDU rule: - PII / Advanced Matching: - Event list: ## Governance recommendation - ... ## Recommended next step - ... ``` ### If you are in direct-implementation mode ```markdown # Analytics SDK implementation ## Bootstrap location - file/path - why this is the shared render point ## Current state by platform - TikTok: - Meta: ## Cross-platform decisions - ... ## What was unified - ... ## Intentional platform-specific differences - ... ## Ownership / source of truth - ... ## Privacy / compliance decisions - CSP: - Consent gating: - LDU: - Advanced Matching: ## Event mapping implemented - business action -> TikTok event -> Meta event -> code location ## TikTok vs Meta gaps that remain - ... ## Verification - per-platform correctness holds - cross-platform consistency is improved or explicitly bounded - bootstrap initializes once per platform - target events fire once at the correct business moment - privacy gates behave as intended ``` ## Reference routing If the task involves: - bootstrap placement, event payloads, event mapping, or platform-specific implementation details → read `references/install-and-events.md` - CSP, consent behavior, LDU, Advanced Matching / PII, or shared-vs-platform-specific privacy rules → read `references/privacy-and-csp.md` Keep vendor snippets, payload examples, and low-level policy details in references, not in this main skill file. ## Pre-implementation gate Before writing code, confirm all of the following: - The target app or site is identified. - A shared render path or existing analytics abstraction is identified. - Current state by platform is classified. - Governance state is classified. - Any duplicate-init ownership is understood well enough to modify safely. - Blocking privacy questions are resolved or the work is constrained to a safe non-sensitive subset. - The chosen execution mode is still correct. If any item fails, do not proceed with broad implementation. ## Post-implementation verification Before finishing, verify two layers of success. ### Per-platform correctness - Each platform is initialized at most once. - Initialization lives in a global/shared location. - No init/load calls remain in components or click handlers unless intentionally wrapped and justified. - Page-view behavior is present only where expected and does not duplicate. - Purchase and other commerce events include required fields such as `currency` and `value` when applicable. - Privacy gates behave as intended and were not bypassed. ### Cross-platform consistency - Event names and key parameters are aligned across TikTok and Meta only where business semantics match. - Differences that remain are intentional and documented. - Ownership and source of truth are preserved or clarified. - The implementation matches the relevant reference files where applicable.

path: evals/evals.json
content: {
  "skill_name": "analytics-sdk-setup",
  "evals": [
    {
      "id": 1,
      "prompt": "In our Next.js storefront repo, TikTok Pixel seems to load twice on checkout and Meta only loads once. Please fix the duplicate Pixel initialization without changing unrelated tracking code.",
      "expected_output": "The skill should explicitly choose Mode A only if ownership, bootstrap location, and privacy blockers are already clear from the repo. It should keep the fix localized, inspect duplicate-init ownership first, and avoid broad tracking refactors.",
      "files": []
    },
    {
      "id": 2,
      "prompt": "Compare TikTok and Meta tracking in this repo and tell me where they drift. I want to understand whether event timing, ownership, and source of truth are aligned before we edit anything.",
      "expected_output": "The skill should explicitly choose Mode B, inspect the repo before proposing edits, classify current governance state, and produce an audit or plan that covers per-platform correctness, cross-platform consistency, and ownership.",
      "files": []
    },
    {
      "id": 3,
      "prompt": "Add TikTok and Meta Purchase tracking to our checkout success flow, but I do not know whether Pixel IDs, consent gating, or CSP changes are already configured.",
      "expected_output": "The skill should explicitly choose Mode C, ask only the minimum blocking questions, stay privacy-conservative, and avoid inventing Pixel IDs, consent rules, CSP allowlists, LDU behavior, or PII handling.",
      "files": []
    }
  ]
}


path: SKILL.zh-CN.md
content: ---
name: analytics-sdk-setup
description: 当用户希望编码代理在真实 repo 中审计、安装、对账、对齐或修复 TikTok Pixel 和/或 Meta Pixel 代码时使用此技能——尤其适用于重复初始化、tracking 漂移、事件映射、consent/CSP/LDU/隐私 gating，或 analytics ownership 不清晰的场景。
---

# Analytics SDK 设置

当用户希望编码代理在真实代码库中检查、安装、比较、对齐、对账或修复 TikTok Pixel 和 Meta Pixel 跟踪时，使用此技能。

即使用户没有直接提到这个技能名，只要真实需求是 repo 级别的 Pixel 调试或对齐工作，例如重复初始化、page-view 行为异常、tracking 漂移、事件映射、consent/CSP 审查，或 source of truth 清理，也应激活这个技能。

这个技能面向 Claude Code、Cursor 以及类似的 repo-aware 编码代理。代理不能只是盲贴 snippet，而是必须先检查仓库、找到共享 bootstrap 位置、避免重复初始化、保留现有有效集成，并在启用敏感跟踪前明确隐私 / 合规决策。

## 配套 prompt

如果当前环境不会直接加载 `SKILL.md`，而是只接受单个 prompt block，请使用：
- `agent-system-prompt.md`

将 `SKILL.md` 视为规范的主技能说明，将 `agent-system-prompt.md` 视为紧凑的运行时摘要。

## 使用示例

这个技能适用于下面这类请求：
- "Compare TikTok and Meta tracking in this repo and tell me where they drift."
- "Fix duplicate Pixel initialization and keep TikTok and Meta aligned."
- "Add Purchase tracking for TikTok and Meta using the same business moment and shared contract."
- "Audit ownership, consent gating, and source of truth for TikTok and Meta events."

如果用户只是想要概念解释，而不是 repo 分析或实现，不要使用这个技能。

## 核心目标

这个技能不只是为了安装或修一个单独的 Pixel。

它的核心目标，是帮助代理把 TikTok 和 Meta 当作一个双平台跟踪系统来处理：
- 验证每个平台本身是否正确
- 评估跨平台一致性
- 识别 ownership 和 source of truth
- 判断哪些应该统一
- 判断哪些应该保持平台差异

示例或 reference 中可能先写 TikTok，但这个技能的范围并不局限于 TikTok。只要任务同时涉及两个平台，任何实现、审计或修复都应该同时考虑两边。

## 必须先做的第一步

在做任何事情之前，你 MUST：
1. 先判断执行模式（`Mode A`、`Mode B` 或 `Mode C`）
2. 明确输出所选模式
3. 用 1-2 行说明原因

在完成这一步之前，DO NOT 编写任何代码。

## 快速修复模式

如果用户请求显然很窄，例如修复重复初始化，或只新增一个事件：
- 可以跳过完整的治理分析
- 优先关注局部正确性
- 只有在用户明确提到两个平台，或者这个局部改动显然会制造漂移时，才检查跨平台对齐

只有在任务范围确实足够窄、且隐私 blocker 也都已解决时，才能使用 quick-fix 判断。

Quick fix mode 不会绕过 output contract。你仍然要保留所选模式要求的必要章节，只是可以把非关键治理部分写得更简短，或标记为不适用。

## 思考步骤（必须遵守）

1. 用户在要求什么？
2. repo 是否可用？
3. 是否存在 blocker？
4. 选择执行模式。
5. 然后再继续。

## 何时激活

当用户提出以下任一请求时，激活此技能：
- 安装或修复 TikTok Pixel 或 Meta Pixel
- 对齐、对账或比较 TikTok 和 Meta 的事件跟踪
- 调查重复 Pixel 初始化、page-view 行为异常或 tracking 漂移
- 配置事件映射、参数映射、去重或 Advanced Matching
- 审查 CSP、LDU、consent 或与 PII 相关的约束
- 审计现有 analytics 集成是否正确
- 清理 repo 中 analytics ownership 或 source of truth
- 让 Cursor、Claude Code 之类的编码代理直接实现或调试 Pixel 集成
- 产出关于 TikTok / Meta 跟踪治理或对账的建议

即使用户没有说出“analytics-sdk-setup”，只要明显需要 repo-aware 的 Pixel 检查、修复或对齐，也应该激活。

## 何时不要激活

如果用户只是想要以下内容，不要启动完整执行流程：
- 概念解释、文档帮助或术语澄清
- TikTok Pixel 和 Meta Pixel 的高层理论差异
- 不涉及代码库的营销策略讨论
- 分析报表类工作，而不是 SDK / Pixel 集成与修复

如果用户只想要解释，直接回答即可，不要运行完整技能流程。

## 跨平台决策框架

当任务同时涉及 TikTok 和 Meta 时，始终通过以下四个视角评估工作：

1. `Per-platform correctness`
   - 每个平台是否都安装正确、只初始化一次，并在正确的业务时机发送事件？

2. `Cross-platform consistency`
   - 两个平台是否用兼容的时机和核心语义表示同一个业务动作？

3. `Ownership and source of truth`
   - 哪个文件、模块、wrapper、provider 或 tag manager 拥有 bootstrap、事件映射、隐私 gating 和参数 contract？

4. `Governance over local fixes`
   - 一个局部修复会改善整个双平台系统，还是会加剧 TikTok 和 Meta 之间的漂移？

如果局部修复会让双平台治理更差，优先给出 plan 或治理建议，而不是做狭窄 patch。

## Execution mode decision

在提出代码改动前，必须准确选择一种执行模式。

### Mode A: Direct implementation

只有在以下条件全部满足时，才能直接实现：
- repo 可用，并且目标 app 或 site 可以识别。
- 能够定位共享 bootstrap 位置，或已有 analytics abstraction。
- 平台范围明确：TikTok、Meta 或两者。
- Pixel ID 已提供，或者 repo 内已经有可信配置来源。
- 目标环境、域名、页面范围或 route 范围足够明确，可以安全实现。
- 请求足够具体，例如安装 bootstrap、修复重复初始化，或新增某个明确事件。
- 不存在会迫使代理去猜 consent、LDU 或 PII 行为的隐私 blocker。

### Mode B: Plan first

如果代码库可用，但工作仍偏设计型，应使用 plan-first，例如：
- 共享 render path 不明显。
- repo 包含多个 app、品牌、域名，或多个可能的接入点。
- 用户想要的是广义的 TikTok / Meta 事件对齐，而不是单一修复。
- 代理需要先把业务动作映射到事件，再改代码。
- 当前集成在 wrapper、provider、inline snippet 或 tag-manager ownership 之间混杂，需要先审查。
- 主要任务是比较、治理审查或对账，而不是一个狭窄实现。

在这个模式下，你 MUST NOT 修改代码或提出 patch。

### Mode C: Questions first

如果存在 blocker，先问最少但高价值的问题，包括：
- Pixel ID 缺失，且 repo 中没有可靠配置来源。
- Consent、LDU 或 PII / Advanced Matching 要求未知，而这些会影响实现行为。
- 目标 app、环境、route 范围或 rollout 范围不明确。
- 现有 analytics provider 或 tag-manager ownership 不清楚。
- 用户想对齐事件，但背后的业务语义仍然模糊。

在这个模式下，你 MUST NOT 提出实现方案或代码。

如果不确定，优先遵循：
1. 先 audit，后 implementation
2. 先 plan，后 broad refactor
3. 优先保留现有隐私行为，而不是启用新的 tracking
4. 优先做最小 bootstrap 修复，而不是推测式事件扩张

## Required inputs and blocking conditions

在进行实质性改动前，先收集或确认这些输入。

### Required for direct implementation
- 涉及哪些平台：TikTok、Meta 或两者
- Pixel ID，或现有可信配置来源
- 目标 app、域名、页面或 route group
- 目标环境：仅生产、也包含 staging，还是全部环境
- Pixel 是全局加载，还是只在选定页面加载
- 如果请求涉及事件实现，需要明确要跟踪哪些业务事件

### Blocking conditions

如果以下任一问题未解决，不要直接实现敏感或有歧义的行为：
- 是否启用了 CSP，以及 tracking 改动是否需要修改 CSP
- 是否已有 consent gating，或应该 gate load 还是 gate event dispatch
- 是否适用 LDU，以及它是 pixel-wide 还是 event-specific
- 是否允许 Advanced Matching / PII
- 是否存在单一共享 bootstrap 位置
- 是否已有 GTM / analytics provider / wrapper 拥有这部分集成
- TikTok 和 Meta 是否应该共享一个 business-event contract，还是在某段流程中故意分叉

如果存在 blocker，切换到 plan-first 或 questions-first，不要猜。

## Safe defaults and conservative behavior

当信息不完整时，使用以下保守默认：
- 不要编造 Pixel ID、事件语义、consent 规则、CSP allowlist、LDU 策略或 PII 来源。
- 默认不要启用 Advanced Matching / PII。
- 除非规则明确，否则不要启用 LDU。
- 如果事件范围不清楚，把工作限制在 bootstrap placement、重复审计或 plan。
- 如果环境范围不清楚，优先复用 repo 中已有的 env gating，而不是发明新策略。
- 如果 repo 已有 analytics config、隐私工具或 wrapper，优先复用，而不是绕过。
- 如果 SPA 中 page-view 语义不明确，不要推测性地添加 route-change tracking。
- 在得到明确批准前，让隐私敏感行为保持关闭。
- 不要在某些平台差异本来就是有意或必须时，强行做对称统一。

## Repo inspection workflow

在添加或移动 SDK 代码之前，始终先检查现有代码。

按以下顺序执行：
1. 找出用户真正希望被跟踪的目标 app、site 或 package。
2. 判断页面如何产出：共享 HTML template、SSR layout、SPA shell、Next.js layout，还是已有 analytics provider。
3. 找到最合适的共享 bootstrap 位置。
4. 搜索现有 TikTok 和 Meta 初始化。
5. 搜索现有事件分发、helper wrapper、route-change hook 以及 tag-manager bridge。
6. 确认以下内容的 ownership 和 source of truth：
   - bootstrap placement
   - event taxonomy
   - parameter contract
   - consent 或 privacy gating
   - tag-manager 与 app-code 的边界
7. 将治理状态分类为以下之一：
   - `single-platform only`
   - `dual-platform but ungoverned`
   - `platform-correct but cross-platform drifted`
   - `aligned with intentional platform-specific differences`
   - `privacy/governance blocked`
8. 如有必要，记录工程标签，例如：
   - duplicate initialization
   - event-only mismatch
   - privacy / gating mismatch
   - wrapper conflict
   - CSP blocked
9. 如果 repo 证据改变了最初判断，重新选择执行模式。

## Duplicate detection protocol

在改任何东西之前，同时检查 direct call 和 wrapped integration。

### Search for direct init and page-view calls
- TikTok bootstrap: `ttq.load(`
- TikTok base page view: `ttq.page(`
- Meta bootstrap: `fbq('init'`
- Meta page view: `fbq('track', 'PageView'`

### Also inspect wrapper-level ownership
检查：
- analytics provider 组件
- 包装 `ttq` 或 `fbq` 的 helper function
- tag-manager bridge
- root layout 或 app-shell 的 script injection helper
- 可能导致 page-view 重复的 route-change hook

### Treat these as duplicate-risk scenarios
以下情况都应视为重复风险：
- 同一个平台从多个 layout、template 或 app shell 初始化。
- bootstrap 和 SPA route hook 同时发送 base page-view，且意图不明确。
- 某个组件 mount 或 click handler 也初始化了 SDK。
- inline snippet 与更高层的 provider 或 GTM 管理集成并存。

### Consolidation rule
如果发现重复初始化且 ownership 明确：
1. 在最佳共享位置保留一个初始化。
2. 删除其他 init / load 调用。
3. 保留现有有效事件跟踪，除非事件本身也有问题。
4. 只有在不会引入更大 refactor 的情况下，才复用或收敛配置。

如果 ownership 不明确，不要自动合并冲突集成。切换到 plan-first 或 questions-first。

## Implementation workflow

只有在 direct-implementation 模式下使用这个流程。

1. 每个平台只保留或创建一个共享 bootstrap 位置。
2. 优先使用已有的全局 layout、base template、app shell 或 analytics provider，而不是分散 snippet。
3. 尽量复用已有 config、环境开关、consent 工具和隐私 wrapper。
4. 在扩展事件代码前，先修复重复初始化。
5. 在映射到 TikTok / Meta 细节之前，先定义或保留共享 business-event contract。
6. 只在真实业务成功点新增或规范事件调用。
7. 只有在两个平台明确表示同一业务动作时，才对齐 payload。
8. 改动保持最小、局部，并只围绕 tracking。
9. 优先修复坏掉的事件调用，而不是重新安装整个 SDK。

Do not:
- 在 UI 组件、click handler 或重复页面脚本里初始化
- 因为别处 tracking 出问题，就再加一个 init / load
- 在没有明确必要时，用 raw snippet 替换合规 wrapper
- 做与 tracking 无关的广泛重构
- 仅因为一个平台本地正确，就声称双平台治理已完成

如果需要 bootstrap placement、事件命名、映射、payload 示例和验证细节，请在实现事件相关改动前查看 `references/install-and-events.md`。

## Plan-only workflow

当 repo 可用，但实现还不该开始时，使用这个流程。

输出一个简洁但可直接落地的报告，包含：
- 已确认的平台范围
- 可能的共享 bootstrap 位置
- 各平台当前状态
- 治理状态
- duplicate-init 发现
- 现有 privacy / consent / CSP 约束
- 按业务动作整理的 draft event mapping
- 明确 blocker 和推荐下一步

如果主要任务仍然是架构、范围选择、事件设计或跨平台治理，优先给出 plan，而不是直接编辑。

## Ownership and source of truth

当同时涉及 TikTok 和 Meta 时，识别并报告：
- bootstrap ownership 在哪里
- event taxonomy 在哪里定义
- mapping rule 在哪里定义
- privacy gate 在哪里生效
- GTM、app code、wrapper 或 backend logic 是否分别拥有系统不同部分

如果 ownership 是分裂的，plan 或 implementation report 应明确说明这种分裂是有意的、临时的，还是当前漂移的根源。

## Privacy and compliance guardrails

在启用敏感行为前，必须显式检查隐私约束。

- 如果项目里已有 consent 或 privacy 工具，优先复用。
- 不要编造 CSP allowlist。
- 不要编造 LDU 逻辑或区域规则。
- 未经明确批准，也没有合法 first-party 数据来源时，不要启用 Advanced Matching / PII。
- 不要绕过现有法律、consent 或地区审查流程。
- 如果实现会改变敏感行为而政策又不明确，就停下来提问。
- 如果同时涉及 TikTok 和 Meta，检查它们是否应该受同一套共享隐私策略控制。

如果需要 CSP、consent gating、LDU、identifier handling 和共享隐私治理细节，请在实现这些改动前查看 `references/privacy-and-csp.md`。

## Output contract

使用以下结果结构之一。

### If you are in questions-first mode

```markdown
# Analytics SDK questions

## What blocks implementation
- ...

## Decisions that affect both TikTok and Meta
- ...

## Required answers
1. ...
2. ...
3. ...

## Safe progress so far
- ...
```

提问时只问最少但高价值的问题。如果真正阻塞实现的只有 2-3 个答案，不要把完整输入清单全抛出来。

### If you are in plan-first mode

```markdown
# Analytics SDK setup plan

## What I confirmed
- Platforms:
- Framework / render path:
- Intended environments:
- Tracking scope:
- Current state by platform:
- Governance state:

## TikTok vs Meta gaps
- ...

## What to unify
- ...

## What remains platform-specific
- ...

## Ownership / source of truth
- ...

## Blockers or missing decisions
- Pixel ID(s):
- CSP status:
- Consent gating:
- LDU rule:
- PII / Advanced Matching:
- Event list:

## Governance recommendation
- ...

## Recommended next step
- ...
```

### If you are in direct-implementation mode

```markdown
# Analytics SDK implementation

## Bootstrap location
- file/path
- why this is the shared render point

## Current state by platform
- TikTok:
- Meta:

## Cross-platform decisions
- ...

## What was unified
- ...

## Intentional platform-specific differences
- ...

## Ownership / source of truth
- ...

## Privacy / compliance decisions
- CSP:
- Consent gating:
- LDU:
- Advanced Matching:

## Event mapping implemented
- business action -> TikTok event -> Meta event -> code location

## TikTok vs Meta gaps that remain
- ...

## Verification
- per-platform correctness holds
- cross-platform consistency is improved or explicitly bounded
- bootstrap initializes once per platform
- target events fire once at the correct business moment
- privacy gates behave as intended
```

## Reference routing

如果任务涉及：
- bootstrap placement、event payload、event mapping 或 platform-specific implementation detail → 阅读 `references/install-and-events.md`
- CSP、consent behavior、LDU、Advanced Matching / PII，或 shared-vs-platform-specific privacy rule → 阅读 `references/privacy-and-csp.md`

把 vendor snippet、payload example 和低层策略细节都放在 reference 里，不要再塞回这个主文件。

## Pre-implementation gate

在写代码前，确认以下全部成立：
- 目标 app 或 site 已识别。
- 已识别共享 render path 或现有 analytics abstraction。
- 已完成各平台当前状态分类。
- 已完成治理状态分类。
- 对 duplicate-init 的 ownership 已有足够把握，可以安全修改。
- 阻塞性的隐私问题已解决，或任务已被限制在安全、非敏感的子范围内。
- 当前选择的执行模式仍然正确。

如果其中任何一项失败，不要进行大范围实现。

## Post-implementation verification

结束前，从两个层面验证成功。

### Per-platform correctness
- 每个平台最多只初始化一次。
- 初始化位于全局 / 共享位置。
- 除非是有意为之且能解释清楚，否则组件或 click handler 中不应再残留 init / load 调用。
- Page-view 行为只出现在预期位置，且不会重复。
- 当适用时，Purchase 等 commerce 事件包含 `currency` 和 `value` 等必要字段。
- 隐私 gate 行为符合预期，没有被绕过。

### Cross-platform consistency
- 只有在业务语义一致时，TikTok 和 Meta 的事件名与关键参数才需要对齐。
- 保留下来的差异必须是有意且被说明的。
- Ownership 和 source of truth 要被保留或澄清。
- 实现应与相关 reference 文件保持一致。


path: references/privacy-and-csp.zh-CN.md
content: # 隐私、CSP 与数据处理

当任务涉及 TikTok 和 Meta 的 CSP allowlist、consent 行为、limited-data handling、restricted-data policy、Advanced Matching / PII 或跨平台隐私治理时，使用此 reference。

## 何时阅读此文件

当你需要以下任一内容时，阅读此文件：
- Pixel 加载相关的 CSP directive 指南
- 关于 bootstrap、event 或 identifier 的 consent-gating 决策
- Limited Data Use 或 restricted-data handling 指南
- Advanced Matching / PII 要求与 identifier 规则
- TikTok 和 Meta 的共享隐私策略指导

如果任务只涉及 bootstrap placement、event mapping、payload example 或 install verification，优先阅读 `references/install-and-events.md`。

## 跨平台隐私审查视角

当任务同时涉及 TikTok 和 Meta 时，从两个层面审查隐私决策：
- shared policy layer
- platform-specific adapter layer

在 shared policy layer，确认：
- consent 是否必须先于加载或发送事件
- restricted-data handling 是适用于全部流量，还是只适用于某个子集
- 是否允许使用 identifier 做 matching
- 由哪个系统拥有这个决策：app code、wrapper、GTM、backend 还是 privacy platform

在 platform-specific layer，确认：
- 共享决策如何映射到 TikTok 行为
- 共享决策如何映射到 Meta 行为
- 是否有某个平台绕过了另一个平台正在遵守的更严格规则

除非这种差异是有意且已记录的，否则不要让一个平台在隐私敏感行为上默默跑得比另一个更远。

## Consent-gating 选择

在实现隐私敏感行为之前，先决定是 gate 哪一层：
- **Gate load** — 在 consent 授权前不加载 Pixel。
- **Gate send** — 加载 bootstrap，但在 consent 授权前抑制事件发送。
- **Gate identify** — 在政策允许的情况下可以保留非 PII 跟踪，但在获得 consent / legal basis 之前，不发送 `ttq.identify(...)` 或其他 matching signal。

记录当前使用的是哪一种 gate，以及这个决策在哪里生效。

当 TikTok 和 Meta 同时在范围内时，优先先做一份共享策略决策，然后再映射到各自平台 adapter。

## CSP 审查流程

如果站点启用了 Content Security Policy，检查 TikTok Pixel 资源与上报端点是否需要加入 allowlist。

检查以下 directive：
- `frame-src`
- `script-src`
- `img-src`
- `connect-src`

TikTok CSP 指南表明，集成可能需要如下 allowlist 条目：
- `frame-src`: `bytedance:` 和 `sslocal:`
- `script-src`、`img-src` 和 `connect-src` 中可能包括：
  - `analytics.tiktok.com`
  - `analytics-ipv6.tiktokw.us`
  - `ads.tiktok.com`

Guidance：
- 只修改最少必要的 directive。
- 清楚说明到底是哪个 directive 阻止了 Pixel。
- 区分哪些改动已经确认，哪些仍需要用户的安全团队审查。
- 如果实际被拦截的资源与指南不同，以当前官方文档和观察到的浏览器错误为准。

## TikTok 与 Meta 的隐私决策矩阵

当任务同时涉及两个平台时，把下表作为最小治理矩阵使用。

| Concern | Shared governance question | TikTok note | Meta note |
|---|---|---|---|
| CSP / resource loading | 实际被阻止的是哪些 directive 或域名？ | 检查 TikTok 的资源 allowlist 和观察到的错误。 | 检查 Meta 的资源 allowlist 和观察到的错误。 |
| Consent gating | 两个平台是否都应该用同样的 gate load / gate send 行为？ | 判断是 gate bootstrap、event，还是 identifier。 | 判断是 gate bootstrap、event，还是 identifier。 |
| Restricted-data handling | restricted-data 逻辑适用于所有流量，还是只适用于部分流量？ | TikTok LDU 可以是 pixel-wide，也可以是 event-level。 | Meta 可能需要它自己的 restricted-data 或 data-processing 控制。 |
| Matching / identifiers | 是否允许使用 email、phone 或 external identifier？ | `ttq.identify(...)` 必须遵循 consent 与 first-party 规则。 | Meta matching 必须遵循同一份共享隐私决策，即使实现方式不同。 |
| Shared policy source | 规范隐私规则的 source of truth 在哪里？ | 优先使用消费共享 policy signal 的 adapter。 | 优先使用消费同一 policy signal 的 adapter。 |

不要假设 TikTok 的实现天然就定义了正确的 Meta 实现，反之亦然。

## Limited Data Use (LDU)

在启用数据发送之前，明确判断用户是否有 LDU 义务。

先问：
- 他们是否在适用 LDU 的地区或场景中运营？
- 现有 frontend / backend 里是否已经有标记 restricted traffic 的逻辑？
- LDU 应该由地区、consent 状态、账户类型，还是其他业务规则决定？

来自 TikTok 指南的实现细节：
- TikTok 的 LDU 指南把该特性描述为支持某些美国州隐私 opt-out 场景；在实现前，请先核对官方文档中当前实际覆盖的地区。
- 有两种实现模式：
  - 对该 pixel 下所有事件启用 LDU：`ttq.load('<PIXEL_ID>', { limited_data_use: true })`
  - 对单个事件启用 LDU：`ttq.track('Purchase', { limited_data_use: true })`
- 如果只有部分流量受限，优先选择 per-event LDU。
- 只有当用户策略确实适用于该 pixel 下所有事件时，才选择 pixel-wide LDU。

跨平台治理说明：
- 如果 TikTok 和 Meta 同时在范围内，先定义 restricted-data 逻辑是否属于 shared policy layer。
- 然后记录每个平台 adapter 如何表达这份 policy。
- 如果 repo 只在某一个平台支持 restricted-data handling，明确指出这种不对称。

## Advanced Matching / PII

Advanced Matching 需要显式批准。

在启用之前先问：
- 是否要发送 `email`、`phone_number`、`external_id` 或其他 identifier？
- 这些值从哪里来？
- 它们是否已经标准化或哈希？
- 是否具备将这些数据用于广告衡量的 consent？

判断 advertiser 是否可以使用 PII 的原则：
- 只能使用 advertiser 通过自身 first-party 流程已经收集到的 identifier，例如 signup、login、checkout、lead form、CRM-backed 已登录资料，或其他用户明确参与的 account / session 流程。
- 如果 advertiser 无法指出合法的 first-party 来源和 consent / legal basis，就不要启用 Manual Advanced Matching。
- 优先使用已经存在于应用状态、session、checkout 数据或确认提交的表单中的值；不要发明、抓取或推断 identifier。
- 官方文档讨论的是 `external_id`，不是 `external_pii`。如果用户说的是 `external_pii`，先确认他们是不是其实指 first-party external user identifier。

advertiser 可以从哪里获得各类 identifier：
- `email`: login、signup、checkout、newsletter 或其他 advertiser 已拥有的 first-party form / profile 数据
- `phone_number`: checkout、signup、support / contact 或 profile 流程中已收集的手机号
- `external_id`: advertiser 控制的 first-party user / customer identifier，例如内部账号 ID 或 CRM/customer ID

来自 TikTok 指南的实现细节：
- 对于 manual Advanced Matching，应把 `ttq.identify(...)` 放在对应 `ttq.track(...)` 调用之前。
- 指南中支持的 identifier 包括 `email`、`phone_number` 和 `external_id`。
- 原始 `email` 和 `phone_number` 可以交给 TikTok 在客户端做哈希，但前提是 advertiser 的隐私政策、consent 状态和 legal basis 允许这样做。
- 如果手动传入哈希值，遵循指南中的字段级哈希规则；指南指定的是 **SHA-256**。
- Email 哈希要求：哈希前先转小写，并去掉首尾空格。
- Phone number 要求：哈希前先标准化为 **E.164** 格式。
- External ID 要求：哈希前去掉首尾空格。

跨平台治理说明：
- 如果 TikTok 和 Meta 同时在范围内，先决定 shared policy layer 是否允许 matching。
- 然后决定两个平台是否都接收 identifier，还是只让其中一个接收。
- 即使 matching 被推迟或只在一个平台启用，也应保留非 PII 路径。

## 共享策略与平台适配器

当两个平台同时存在时，优先采用以下治理模型：
1. 只定义一次 shared privacy rule
2. 确认这份规则的 source of truth
3. 把规则映射成 TikTok 行为
4. 把同一规则映射成 Meta 行为
5. 记录任何有意的平台差异

如果 repo 已有 consent manager、privacy abstraction 或 GTM 管理的 privacy layer，优先复用，而不是再发明一条新的平行隐私路径。

## Reference pattern for Manual Advanced Matching

```javascript
ttq.identify({
    email: '0c7e6a405862e402eb76a70f8a26fc732d07c32931e9fae9ab1582911d2e8a3b',
    phone_number: '9f7ec22d72092cd3c0b58726ed9c2d91b92e51a3f29837508fb2948bb22dd2fd',
    external_id: '936a185caaa266bb9cbe981e9e05cb78cd732b0b3280eb944412bb6f8f8f07af',
})

ttq.track('CompleteRegistration')
```

## Rules

- 默认不要启用 PII reporting。
- 只有在用户明确要求、且隐私规则允许时，才复用已有 user / profile / session 数据。
- 即使 Advanced Matching 被推迟，也要保留非 PII bootstrap 路径。
- 不要绕过用户现有的 consent 或法律审查流程。
- 只在确实拥有所需 identifier 的页面 / 事件上发送 `ttq.identify(...)`。
- 如果 TikTok 和 Meta 同时在范围内，检查是否有某个平台在一条另一个平台并不共享的规则下接收了 identifier。


path: references/privacy-and-csp.md
content: # Privacy, CSP, and data handling

Use this reference when the task involves CSP allowlists, consent behavior, limited-data handling, restricted-data policies, Advanced Matching / PII, or cross-platform privacy governance for TikTok and Meta.

## When to read this file

Read this file when you need one of the following:
- CSP directive guidance for Pixel loading
- consent-gating decisions for bootstrap, events, or identifiers
- Limited Data Use or restricted-data handling guidance
- Advanced Matching / PII requirements and identifier rules
- shared privacy-policy guidance across TikTok and Meta

If the current task is only about bootstrap placement, event mapping, payload examples, or install verification, prefer `references/install-and-events.md` first.

## Cross-platform privacy review lens

When TikTok and Meta are both in scope, review privacy decisions at two levels:
- the shared policy layer
- the platform-specific adapter layer

At the shared policy layer, confirm:
- whether consent is required before loading or sending events
- whether restricted-data handling applies to part or all of the traffic
- whether identifiers may be used for matching
- which system owns the decision: app code, wrapper, GTM, backend, or privacy platform

At the platform-specific layer, confirm:
- how the shared decision is translated into TikTok behavior
- how the shared decision is translated into Meta behavior
- whether one platform is bypassing a stricter rule applied to the other

Do not let one platform silently outrun the other on privacy-sensitive behavior unless that difference is intentional and documented.

## Consent-gating choices

Before implementing privacy-sensitive behavior, decide which layer is gated:
- **Gate load** — do not load the Pixel before consent is granted.
- **Gate send** — load the bootstrap but suppress event dispatch until consent is granted.
- **Gate identify** — allow non-PII tracking where policy permits, but withhold `ttq.identify(...)` or other matching signals until consent/legal basis exists.

Document which gate is in use and where that decision is enforced.

When TikTok and Meta are both in scope, prefer one shared policy decision first, then map it into each platform adapter.

## CSP review workflow

If the site has Content Security Policy, check whether TikTok Pixel resources and reporting endpoints need allowlisting.

Inspect directives such as:
- `frame-src`
- `script-src`
- `img-src`
- `connect-src`

The TikTok CSP guide shows that integrations may need allowlist entries such as:
- `frame-src`: `bytedance:` and `sslocal:`
- `script-src`, `img-src`, and `connect-src` entries such as:
  - `analytics.tiktok.com`
  - `analytics-ipv6.tiktokw.us`
  - `ads.tiktok.com`

Guidance:
- Patch only the minimum required directives.
- Explain exactly which directive blocks the Pixel.
- Separate confirmed changes from items the user's security team still needs to review.
- If the actual blocked resources differ from the guide, trust the current official docs and observed browser errors.

## TikTok vs Meta privacy decision matrix

Use this as a minimal governance matrix when both platforms are in scope.

| Concern | Shared governance question | TikTok note | Meta note |
|---|---|---|---|
| CSP / resource loading | Which directives or domains are actually blocked? | Review TikTok resource allowlists and observed errors. | Review Meta resource allowlists and observed errors. |
| Consent gating | Should load and send behavior be gated the same way on both platforms? | Decide whether to gate bootstrap, events, or identifiers. | Decide whether to gate bootstrap, events, or identifiers. |
| Restricted-data handling | Does restricted-data logic apply to all traffic or only a subset? | TikTok LDU can be pixel-wide or event-level. | Meta may require its own restricted-data or data-processing controls. |
| Matching / identifiers | Are email, phone, or external identifiers allowed at all? | `ttq.identify(...)` must follow consent and first-party rules. | Meta matching must follow the same shared privacy decision, even if implementation differs. |
| Shared policy source | Where is the canonical privacy rule defined? | Prefer adapters that consume a shared policy signal. | Prefer adapters that consume the same shared policy signal. |

Do not assume the TikTok implementation automatically defines the right Meta implementation, or vice versa.

## Limited Data Use (LDU)

Before enabling data sending, explicitly determine whether the user has LDU obligations.

Ask:
- Do they operate in regions or scenarios where LDU applies?
- Is there existing backend/frontend logic that marks restricted traffic?
- Should LDU be decided by region, consent state, account type, or another business rule?

Implementation details from the TikTok guide:
- TikTok's LDU guide describes the feature as support for certain U.S. state privacy opt-out scenarios; verify the currently covered regions in the official doc before implementation.
- There are two implementation modes:
  - enable LDU for all events under the pixel via `ttq.load('<PIXEL_ID>', { limited_data_use: true })`
  - enable LDU per event via `ttq.track('Purchase', { limited_data_use: true })`
- Prefer per-event LDU if only part of the traffic is restricted.
- Prefer pixel-wide LDU only if the user's policy truly applies to all events under that pixel.

Cross-platform governance note:
- If TikTok and Meta are both in scope, first define whether restricted-data logic belongs to a shared policy layer.
- Then document how each platform adapter expresses that policy.
- If the repo only supports restricted-data handling on one platform, call out the asymmetry explicitly.

## Advanced Matching / PII

Advanced Matching needs explicit approval.

Ask before enabling it:
- Do they want to send `email`, `phone_number`, `external_id`, or other identifiers?
- Where do those values come from?
- Are they already normalized or hashed?
- Do they have consent to use them for advertising measurement?

How to decide whether the advertiser can use PII:
- Only use identifiers the advertiser already collects through its own first-party flows, such as signup, login, checkout, lead forms, CRM-backed authenticated profiles, or another user-approved account/session flow.
- If the advertiser cannot point to a legitimate first-party source plus consent/legal basis, do not enable Manual Advanced Matching.
- Prefer values already available in the application state, session, checkout data, or confirmed form submissions; do not invent, scrape, or infer identifiers.
- The official guide discusses `external_id`, not `external_pii`. If the user says `external_pii`, clarify whether they actually mean a first-party external user identifier.

How the advertiser can obtain each supported identifier:
- `email`: from login, signup, checkout, newsletter, or other first-party forms/profile data the advertiser already owns.
- `phone_number`: from checkout, signup, support/contact, or profile flows where the advertiser already collected the user's phone.
- `external_id`: a first-party user or customer identifier controlled by the advertiser, for example an internal account ID or CRM/customer ID.

Implementation details from the TikTok guide:
- For manual Advanced Matching, place `ttq.identify(...)` directly before the related `ttq.track(...)` call.
- Supported identifiers shown in the guide include `email`, `phone_number`, and `external_id`.
- Raw `email` and `phone_number` values can be passed and hashed client-side by TikTok, but only if the advertiser's privacy policy, consent state, and legal basis allow that path.
- If passing hashed values manually, follow the guide's field-specific hashing rules; the referenced guide specifies **SHA-256**.
- Email hashing requirements in the guide: lowercase before hashing and trim leading/trailing spaces.
- Phone number requirements in the guide: normalize to **E.164** format before hashing.
- External ID requirements in the guide: trim leading/trailing spaces before hashing.

Cross-platform governance note:
- If TikTok and Meta are both in scope, first decide whether matching is allowed at the shared policy layer.
- Then decide whether both platforms should receive identifiers, or only one should.
- Keep a non-PII path available even if matching is postponed or enabled only on one platform.

## Shared policy and platform adapters

Prefer this governance model when both platforms are present:
1. define the shared privacy rule once
2. identify the source of truth for that rule
3. map the rule into TikTok behavior
4. map the same rule into Meta behavior
5. document any intentional platform-specific differences

If the repo already has a consent manager, privacy abstraction, or GTM-owned privacy layer, reuse it instead of inventing a new parallel policy path.

## Reference pattern for Manual Advanced Matching

```javascript
ttq.identify({
    email: '0c7e6a405862e402eb76a70f8a26fc732d07c32931e9fae9ab1582911d2e8a3b',
    phone_number: '9f7ec22d72092cd3c0b58726ed9c2d91b92e51a3f29837508fb2948bb22dd2fd',
    external_id: '936a185caaa266bb9cbe981e9e05cb78cd732b0b3280eb944412bb6f8f8f07af',
})

ttq.track('CompleteRegistration')
```

## Rules

- Never enable PII reporting by default.
- Reuse existing user/profile/session data only if the user asked for it and privacy rules allow it.
- Keep the non-PII bootstrap path available even if Advanced Matching is postponed.
- Do not bypass the user's consent or legal review process.
- Only emit `ttq.identify(...)` on pages/events where the needed identifiers are truly available.
- If TikTok and Meta are both in scope, check whether one platform is receiving identifiers under a rule that the other platform does not share.


path: references/install-and-events.md
content: # Install and event details

Use this reference when the task requires exact bootstrap placement guidance, platform event payload examples, event-name lookup, cross-platform mapping support, or install/event verification details.

## When to read this file

Read this file when you need one of the following:
- exact base bootstrap placement guidance
- the minified base code snippet structure
- TikTok or Meta standard event-name reference
- event payload examples for a specific platform event
- a starter mapping table from business action to platform events
- a checklist for install, mapping, and verification review

If the current task is only about CSP, consent gating, LDU, restricted-data handling, or Advanced Matching / PII, prefer `references/privacy-and-csp.md` first.

## Section map

- `## Bootstrap placement and base code` — TikTok bootstrap guidance and baseline install rules
- `## TikTok vs Meta bootstrap comparison` — dual-platform bootstrap comparison and page-view baseline differences
- `## Standard and custom event guidance` — standard TikTok events plus clearly labeled custom/internal examples
- `## Cross-platform event alignment starter table` — business-action-to-platform-event scaffold
- `## Recommended parameters by event` — parameter guidance and field-name caution notes
- `## Payload examples` — concrete `ttq.track(...)`, `ttq.identify(...)`, and `fbq(...)` examples
- `## Gap review checklist` — what to inspect when comparing TikTok and Meta
- `## Verification checklist` — install and event validation steps

## Bootstrap placement and base code

According to TikTok's install guide, the base code should:
- live near the **top of the `<head>` section**
- be pasted as the **full JavaScript base code block**, not as a partial fragment
- include the loader for `https://analytics.tiktok.com/i18n/pixel/events.js`
- call `ttq.load('<PIXEL_ID>')`
- call `ttq.page()` to emit the base page view event used for installation verification

Treat this as the baseline install reference, not as permission to paste the snippet into arbitrary files. The agent should still choose the correct shared render path in the current repo before applying it.

Use this full base code as the reference snippet and replace only `<PIXEL_ID>`.
Prefer compressed/minified basecode examples in this skill unless the user explicitly asks for expanded formatting:

```html
<script>
!function(w,d,t){w.TiktokAnalyticsObject=t;var ttq=w[t]=w[t]||[];ttq.methods=["page","track","identify","instances","debug","on","off","once","ready","alias","group","enableCookie","disableCookie"],ttq.setAndDefer=function(t,e){t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}};for(var i=0;i<ttq.methods.length;i++)ttq.setAndDefer(ttq,ttq.methods[i]);ttq.instance=function(t){for(var e=ttq._i[t]||[],n=0;n<ttq.methods.length;n++)ttq.setAndDefer(e,ttq.methods[n]);return e},ttq.load=function(e,n){var i="https://analytics.tiktok.com/i18n/pixel/events.js";ttq._i=ttq._i||{},ttq._i[e]=[],ttq._i[e]._v='analytics/0.0.1',ttq._i[e]._u=i,ttq._t=ttq._t||{},ttq._t[e]=+new Date,ttq._o=ttq._o||{},ttq._o[e]=n||{};var o=document.createElement("script");o.type="text/javascript",o.async=!0,o.src=i+"?sdkid="+e+"&lib="+t;var a=document.getElementsByTagName("script")[0];a.parentNode.insertBefore(o,a)};ttq.load('<PIXEL_ID>');ttq.page()}(window,document,'ttq');
</script>
```

Important implementation details:
- Keep the full bootstrap intact.
- Replace only the Pixel ID placeholder before shipping.
- `Page View` is already covered by the base code via `ttq.page()`, so do not add a duplicate page-view event unless the app needs explicit SPA navigation handling.
- `ttq.track(...)` should fire where the business action is known to have succeeded.
- For page-load-based conversion events, put the event on the post-action page that only loads after success.
- For click-driven events, do not fire on raw click unless the click itself is the business success moment.
- If a page contains multiple pixels, the guide shows using `ttq.instance('<pixel_id>').track(...)` for pixel-specific event dispatch.

## TikTok vs Meta bootstrap comparison

Use this section when both platforms are in scope and you need a minimal bootstrap comparison.

| Concern | TikTok | Meta | Governance note |
|---|---|---|---|
| Base init call | `ttq.load('<PIXEL_ID>')` | `fbq('init', '<PIXEL_ID>')` | Keep one shared bootstrap location per platform. |
| Base page view | `ttq.page()` | `fbq('track', 'PageView')` | Avoid duplicating page views with SPA route hooks. |
| Placement goal | shared head/layout/app shell | shared head/layout/app shell | Prefer the same render path strategy when both platforms are enabled. |
| Multi-pixel handling | `ttq.instance(...)` patterns may apply | Meta may use multiple init IDs under the same `fbq` setup | Do not assume multi-pixel ownership is equivalent across platforms. |
| Validation | TikTok helper / diagnostics | Meta Pixel Helper / Events Manager diagnostics | Validate each platform locally, then compare behavior together. |

Treat the platforms symmetrically at the governance level even though the SDK calls differ.

## Standard and custom event guidance

### TikTok standard event names

The install guide includes examples such as:
- `AddPaymentInfo`
- `AddToCart`
- `AddToWishlist`
- `ApplicationApproval`
- `Purchase`
- `CompleteRegistration`
- `Contact`
- `CustomizeProduct`
- `Download`
- `FindLocation`
- `InitiateCheckout`
- `Lead`
- `Schedule`
- `Search`
- `StartTrial`
- `SubmitApplication`
- `Subscribe`
- `ViewContent`

## Cross-platform event alignment starter table

Use this as a planning scaffold before editing many files.

| Business action | TikTok event | Meta event | Shared trigger rule | Shared core fields | Platform-specific notes |
|---|---|---|---|---|---|
| Page view | `ttq.page()` | `PageView` | fire at the canonical page-view moment | page context only if used | SPA route behavior may need explicit handling |
| Product detail view | `ViewContent` | `ViewContent` | after product detail is actually rendered | product identity, value, currency | field shapes can differ |
| Add to cart | `AddToCart` | `AddToCart` | after cart mutation succeeds | product identity, quantity, value, currency | keep trigger moment aligned |
| Checkout start | `InitiateCheckout` | `InitiateCheckout` | when checkout truly starts | cart or commerce context | avoid firing too early |
| Payment info added | `AddPaymentInfo` | `AddPaymentInfo` | after payment info is accepted | value, currency, commerce context | confirm exact success point |
| Purchase success | `Purchase` | `Purchase` | after successful order/payment completion | value, currency, order/product context | deduplication and event identity may differ |
| Lead submit | `Lead` | `Lead` | after successful lead capture | shared lead semantics only | custom mapping may still be needed |
| Registration success | `CompleteRegistration` | `CompleteRegistration` | after confirmed registration success | shared registration context | keep semantics consistent |
| Search | `Search` | `Search` | after actual search action or results state | search term | field shape may differ by implementation |

This is a starter table, not a forced parity table. If one platform requires a custom event or a different field contract, record that explicitly rather than hiding the difference.

## Recommended parameters by event

Examples explicitly called out in the TikTok guide:
- `AddToCart`: `content_type`, `quantity`, `description`, `content_id`, `currency`, `value`
- `Purchase`: `content_type`, `quantity`, `description`, `content_id`, `currency`, `value`
- `ViewContent`: `content_type`, `quantity`, `description`, `content_id`, `currency`, `value`
- `Search`: `query`
- `StartTrial`: `currency`, `value`

Field-name caution for agents:
- Use `query` as the documented baseline for TikTok Search in this reference.
- Some broader analytics implementations or shared cross-platform contracts may instead use `search_string`.
- If the current repo already uses `search_string`, or if the latest official docs for the concrete implementation path differ, prefer the current repo conventions plus official docs over blind normalization.
- Do not present both `query` and `search_string` as simultaneous default recommendations.

Treat these parameter lists as recommended baselines, not as permission to invent unavailable values.

## Payload examples

Use these as payload references when validating or implementing events. Replace placeholders with real values from the user's application.

These are examples, not mandatory one-size-fits-all payloads. Prefer the smallest payload that is correct for the actual business action and data available in the repo.

### TikTok identity example

```js
ttq.identify({
  email: "<hashed_email_address>",
  phone_number: "<hashed_phone_number>",
  external_id: "<hashed_external_id>"
});
```

### TikTok ViewContent

```js
ttq.track('ViewContent', {
  contents: [
    {
      content_id: "<content_identifier>",
      content_type: "<content_type>",
      content_name: "<content_name>"
    }
  ],
  value: "<content_value>",
  currency: "<content_currency>"
});
```

### TikTok AddToWishlist

```js
ttq.track('AddToWishlist', {
  contents: [
    {
      content_id: "<content_identifier>",
      content_type: "<content_type>",
      content_name: "<content_name>"
    }
  ],
  value: "<content_value>",
  currency: "<content_currency>"
});
```

### TikTok Search

```js
ttq.track('Search', {
  query: "<search_keywords>"
});
```

### TikTok AddPaymentInfo

```js
ttq.track('AddPaymentInfo', {
  contents: [
    {
      content_id: "<content_identifier>",
      content_type: "<content_type>",
      content_name: "<content_name>"
    }
  ],
  value: "<content_value>",
  currency: "<content_currency>"
});
```

### TikTok AddToCart

```js
ttq.track('AddToCart', {
  contents: [
    {
      content_id: "<content_identifier>",
      content_type: "<content_type>",
      content_name: "<content_name>"
    }
  ],
  value: "<content_value>",
  currency: "<content_currency>"
});
```

### TikTok InitiateCheckout

```js
ttq.track('InitiateCheckout', {
  contents: [
    {
      content_id: "<content_identifier>",
      content_type: "<content_type>",
      content_name: "<content_name>"
    }
  ],
  value: "<content_value>",
  currency: "<content_currency>"
});
```

### TikTok PlaceAnOrder custom example

```js
ttq.track('PlaceAnOrder', {
  contents: [
    {
      content_id: "<content_identifier>",
      content_type: "<content_type>",
      content_name: "<content_name>"
    }
  ],
  value: "<content_value>",
  currency: "<content_currency>"
});
```

Treat `PlaceAnOrder` as a custom/internal example, not as a documented TikTok standard event.

### TikTok CompleteRegistration

```js
ttq.track('CompleteRegistration', {
  contents: [
    {
      content_id: "<content_identifier>",
      content_type: "<content_type>",
      content_name: "<content_name>"
    }
  ],
  value: "<content_value>",
  currency: "<content_currency>"
});
```

### TikTok Purchase

```js
ttq.track('Purchase', {
  contents: [
    {
      content_id: "<content_identifier>",
      content_type: "<content_type>",
      content_name: "<content_name>"
    }
  ],
  value: "<content_value>",
  currency: "<content_currency>"
});
```

### Meta PageView

```js
fbq('track', 'PageView');
```

### Meta ViewContent

```js
fbq('track', 'ViewContent', {
  content_ids: ["<content_identifier>"],
  content_type: "product",
  value: "<content_value>",
  currency: "<content_currency>"
});
```

### Meta AddToCart

```js
fbq('track', 'AddToCart', {
  content_ids: ["<content_identifier>"],
  content_type: "product",
  value: "<content_value>",
  currency: "<content_currency>"
});
```

### Meta InitiateCheckout

```js
fbq('track', 'InitiateCheckout', {
  value: "<checkout_value>",
  currency: "<checkout_currency>"
});
```

### Meta Purchase

```js
fbq('track', 'Purchase', {
  value: "<order_value>",
  currency: "<order_currency>"
});
```

### Meta Lead

```js
fbq('track', 'Lead', {
  value: "<lead_value>",
  currency: "<lead_currency>"
});
```

## Gap review checklist

When TikTok and Meta are both in scope, inspect whether:
- the same business action is tracked on both platforms when it should be
- both platforms fire at the same business success moment
- the core shared fields are present on both platforms where expected
- a difference is intentional or accidental
- one platform is implemented in app code while the other is owned by GTM or another system
- ownership and source of truth are clear
- page-view behavior is locally correct and cross-platform consistent enough for the business need

## Verification checklist

Validate success at two levels.

### Per-platform verification
- TikTok's install guide specifically recommends checking with:
  - **Pixel Helper**
  - **Test Events and Diagnostics**
  - **Debug Mode**
- Meta integrations should be checked with equivalent browser helper and Events Manager diagnostics where available.

### Cross-platform verification
When reviewing install and event behavior, inspect whether:
- the base bootstrap appears in the intended shared output for each platform
- the expected recommended parameters are present for commerce, search, and trial events when applicable
- the event fires exactly once at the real business success point on each platform
- page-view behavior is not duplicated by bootstrap plus SPA navigation hooks
- multiple-pixel pages dispatch to the intended pixel instance where applicable
- TikTok and Meta remain aligned on shared business semantics even when platform-specific fields differ


path: references/install-and-events.zh-CN.md
content: # 安装与事件细节

当任务需要精确的 bootstrap placement 指南、平台事件 payload 示例、事件名查询、跨平台映射支持或安装 / 事件验证细节时，使用此 reference。

## 何时阅读此文件

当你需要以下任一内容时，阅读此文件：
- 精确的基础 bootstrap placement 指南
- 压缩 / minified base code snippet 结构
- TikTok 或 Meta 标准事件名参考
- 某个具体平台事件的 payload 示例
- 从 business action 到平台事件的 starter mapping table
- 安装、映射与验证审查清单

如果当前任务只涉及 CSP、consent gating、LDU、restricted-data handling 或 Advanced Matching / PII，优先阅读 `references/privacy-and-csp.md`。

## 章节索引

- `## Bootstrap 放置与基础代码` — TikTok bootstrap 指南和基础安装规则
- `## TikTok 与 Meta 的 bootstrap 对比` — 双平台 bootstrap 对比与 page-view 基线差异
- `## 标准事件与自定义事件说明` — TikTok 标准事件，以及明确标注的 custom / internal example
- `## 跨平台事件对齐起步表` — 从 business action 到平台事件的脚手架
- `## 各事件推荐参数` — 参数建议与字段名注意事项
- `## Payload 示例` — `ttq.track(...)`、`ttq.identify(...)` 和 `fbq(...)` 的具体示例
- `## 差异审查清单` — 比较 TikTok 与 Meta 时要检查的内容
- `## 验证清单` — 安装与事件验证步骤

## Bootstrap 放置与基础代码

根据 TikTok 的安装指南，base code 应该：
- 放在 **`<head>` section 顶部附近**
- 以**完整 JavaScript base code block** 形式粘贴，而不是部分片段
- 包含 `https://analytics.tiktok.com/i18n/pixel/events.js` 的 loader
- 调用 `ttq.load('<PIXEL_ID>')`
- 调用 `ttq.page()` 来发送基础 page-view 事件，供安装验证使用

把这部分视为基础安装参考，而不是允许你把 snippet 随便贴进任意文件。代理仍然应该先在当前 repo 中选择正确的共享 render path，再应用它。

下面这段完整 base code 可作为 reference snippet，只替换 `<PIXEL_ID>` 即可。
除非用户明确要求展开格式，否则在此技能中优先使用压缩 / minified basecode 示例：

```html
<script>
!function(w,d,t){w.TiktokAnalyticsObject=t;var ttq=w[t]=w[t]||[];ttq.methods=["page","track","identify","instances","debug","on","off","once","ready","alias","group","enableCookie","disableCookie"],ttq.setAndDefer=function(t,e){t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}};for(var i=0;i<ttq.methods.length;i++)ttq.setAndDefer(ttq,ttq.methods[i]);ttq.instance=function(t){for(var e=ttq._i[t]||[],n=0;n<ttq.methods.length;n++)ttq.setAndDefer(e,ttq.methods[n]);return e},ttq.load=function(e,n){var i="https://analytics.tiktok.com/i18n/pixel/events.js";ttq._i=ttq._i||{},ttq._i[e]=[],ttq._i[e]._v='analytics/0.0.1',ttq._i[e]._u=i,ttq._t=ttq._t||{},ttq._t[e]=+new Date,ttq._o=ttq._o||{},ttq._o[e]=n||{};var o=document.createElement("script");o.type="text/javascript",o.async=!0,o.src=i+"?sdkid="+e+"&lib="+t;var a=document.getElementsByTagName("script")[0];a.parentNode.insertBefore(o,a)};ttq.load('<PIXEL_ID>');ttq.page()}(window,document,'ttq');
</script>
```

Important implementation details:
- 保持完整 bootstrap 不变。
- 上线前只替换 Pixel ID 占位符。
- `Page View` 已经通过 `ttq.page()` 包含在 base code 中，因此除非应用确实需要显式 SPA navigation handling，否则不要再加重复的 page-view 事件。
- `ttq.track(...)` 应该放在可以确认业务动作已经成功的位置。
- 对于基于页面加载的 conversion event，应把事件放在只会在成功后加载的 post-action page 上。
- 对于 click 驱动事件，除非 click 本身就是业务成功时刻，否则不要在原始 click 上触发。
- 如果页面包含多个 pixel，指南展示了使用 `ttq.instance('<pixel_id>').track(...)` 对指定 pixel 发送事件的方式。

## TikTok 与 Meta 的 bootstrap 对比

当任务同时涉及两个平台，并且你需要一个最小 bootstrap 对比时，使用本节。

| Concern | TikTok | Meta | Governance note |
|---|---|---|---|
| Base init call | `ttq.load('<PIXEL_ID>')` | `fbq('init', '<PIXEL_ID>')` | 每个平台只保留一个共享 bootstrap 位置。 |
| Base page view | `ttq.page()` | `fbq('track', 'PageView')` | 避免与 SPA route hook 叠加，导致 page view 重复。 |
| Placement goal | shared head/layout/app shell | shared head/layout/app shell | 当两个平台都启用时，优先采用同样的 render path 策略。 |
| Multi-pixel handling | 可能使用 `ttq.instance(...)` 模式 | Meta 可能在同一套 `fbq` 设置下使用多个 init ID | 不要假设多 pixel ownership 在两个平台上是等价的。 |
| Validation | TikTok helper / diagnostics | Meta Pixel Helper / Events Manager diagnostics | 先分别验证每个平台，再一起比较行为。 |

虽然 SDK 调用不同，但在治理层面应对称地看待这两个平台。

## 标准事件与自定义事件说明

### TikTok standard event names

安装指南中的示例事件包括：
- `AddPaymentInfo`
- `AddToCart`
- `AddToWishlist`
- `ApplicationApproval`
- `Purchase`
- `CompleteRegistration`
- `Contact`
- `CustomizeProduct`
- `Download`
- `FindLocation`
- `InitiateCheckout`
- `Lead`
- `Schedule`
- `Search`
- `StartTrial`
- `SubmitApplication`
- `Subscribe`
- `ViewContent`

## 跨平台事件对齐起步表

在修改很多文件之前，把它当作 planning scaffold 使用。

| Business action | TikTok event | Meta event | Shared trigger rule | Shared core fields | Platform-specific notes |
|---|---|---|---|---|---|
| Page view | `ttq.page()` | `PageView` | 在规范的 page-view 时刻触发 | 如有需要只附带 page context | SPA route 行为可能需要显式处理 |
| Product detail view | `ViewContent` | `ViewContent` | 在产品详情真正渲染完成后触发 | 产品标识、value、currency | 字段形状可能不同 |
| Add to cart | `AddToCart` | `AddToCart` | 在购物车 mutation 成功后触发 | 产品标识、quantity、value、currency | 保持触发时机一致 |
| Checkout start | `InitiateCheckout` | `InitiateCheckout` | 在 checkout 真正开始时触发 | 购物车或 commerce context | 避免触发过早 |
| Payment info added | `AddPaymentInfo` | `AddPaymentInfo` | 在支付信息被接受后触发 | value、currency、commerce context | 确认准确成功点 |
| Purchase success | `Purchase` | `Purchase` | 在订单 / 支付成功完成后触发 | value、currency、订单 / 产品上下文 | 去重与事件身份可能不同 |
| Lead submit | `Lead` | `Lead` | 在 lead 成功采集后触发 | 共享的 lead 语义 | 可能仍需要 custom mapping |
| Registration success | `CompleteRegistration` | `CompleteRegistration` | 在注册成功后触发 | 共享的注册上下文 | 保持语义一致 |
| Search | `Search` | `Search` | 在真实搜索动作或结果状态出现后触发 | 搜索词 | 字段形状可能因实现而异 |

这是一个 starter table，不是强制 parity table。如果某个平台需要 custom event，或需要不同字段 contract，应明确记录，而不是把差异藏起来。

## 各事件推荐参数

TikTok 指南中明确列出的推荐参数示例：
- `AddToCart`: `content_type`, `quantity`, `description`, `content_id`, `currency`, `value`
- `Purchase`: `content_type`, `quantity`, `description`, `content_id`, `currency`, `value`
- `ViewContent`: `content_type`, `quantity`, `description`, `content_id`, `currency`, `value`
- `Search`: `query`
- `StartTrial`: `currency`, `value`

Field-name caution for agents:
- 在此 reference 中，把 `query` 视为 TikTok Search 的文档基线。
- 某些更广义的 analytics 实现或共享 cross-platform contract 也可能使用 `search_string`。
- 如果当前 repo 已经使用 `search_string`，或者该具体实现路径的最新官方文档不同，优先遵循当前 repo 约定和官方文档，而不是机械统一。
- 不要把 `query` 和 `search_string` 同时当作默认推荐值来表达。

这些参数列表只是推荐基线，不代表你可以编造实际不存在的值。

## Payload 示例

当你在验证或实现事件时，把这些作为 payload 参考。请把占位符替换为用户应用中的真实值。

这些只是 example，而不是一套必须照搬的统一 payload。优先选择对当前业务动作和 repo 中可用数据来说最小且正确的 payload。

### TikTok identity example

```js
ttq.identify({
  email: "<hashed_email_address>",
  phone_number: "<hashed_phone_number>",
  external_id: "<hashed_external_id>"
});
```

### TikTok ViewContent

```js
ttq.track('ViewContent', {
  contents: [
    {
      content_id: "<content_identifier>",
      content_type: "<content_type>",
      content_name: "<content_name>"
    }
  ],
  value: "<content_value>",
  currency: "<content_currency>"
});
```

### TikTok AddToWishlist

```js
ttq.track('AddToWishlist', {
  contents: [
    {
      content_id: "<content_identifier>",
      content_type: "<content_type>",
      content_name: "<content_name>"
    }
  ],
  value: "<content_value>",
  currency: "<content_currency>"
});
```

### TikTok Search

```js
ttq.track('Search', {
  query: "<search_keywords>"
});
```

### TikTok AddPaymentInfo

```js
ttq.track('AddPaymentInfo', {
  contents: [
    {
      content_id: "<content_identifier>",
      content_type: "<content_type>",
      content_name: "<content_name>"
    }
  ],
  value: "<content_value>",
  currency: "<content_currency>"
});
```

### TikTok AddToCart

```js
ttq.track('AddToCart', {
  contents: [
    {
      content_id: "<content_identifier>",
      content_type: "<content_type>",
      content_name: "<content_name>"
    }
  ],
  value: "<content_value>",
  currency: "<content_currency>"
});
```

### TikTok InitiateCheckout

```js
ttq.track('InitiateCheckout', {
  contents: [
    {
      content_id: "<content_identifier>",
      content_type: "<content_type>",
      content_name: "<content_name>"
    }
  ],
  value: "<content_value>",
  currency: "<content_currency>"
});
```

### TikTok PlaceAnOrder custom example

```js
ttq.track('PlaceAnOrder', {
  contents: [
    {
      content_id: "<content_identifier>",
      content_type: "<content_type>",
      content_name: "<content_name>"
    }
  ],
  value: "<content_value>",
  currency: "<content_currency>"
});
```

把 `PlaceAnOrder` 视为 custom / internal example，而不是 TikTok 官方文档中的标准事件。

### TikTok CompleteRegistration

```js
ttq.track('CompleteRegistration', {
  contents: [
    {
      content_id: "<content_identifier>",
      content_type: "<content_type>",
      content_name: "<content_name>"
    }
  ],
  value: "<content_value>",
  currency: "<content_currency>"
});
```

### TikTok Purchase

```js
ttq.track('Purchase', {
  contents: [
    {
      content_id: "<content_identifier>",
      content_type: "<content_type>",
      content_name: "<content_name>"
    }
  ],
  value: "<content_value>",
  currency: "<content_currency>"
});
```

### Meta PageView

```js
fbq('track', 'PageView');
```

### Meta ViewContent

```js
fbq('track', 'ViewContent', {
  content_ids: ["<content_identifier>"],
  content_type: "product",
  value: "<content_value>",
  currency: "<content_currency>"
});
```

### Meta AddToCart

```js
fbq('track', 'AddToCart', {
  content_ids: ["<content_identifier>"],
  content_type: "product",
  value: "<content_value>",
  currency: "<content_currency>"
});
```

### Meta InitiateCheckout

```js
fbq('track', 'InitiateCheckout', {
  value: "<checkout_value>",
  currency: "<checkout_currency>"
});
```

### Meta Purchase

```js
fbq('track', 'Purchase', {
  value: "<order_value>",
  currency: "<order_currency>"
});
```

### Meta Lead

```js
fbq('track', 'Lead', {
  value: "<lead_value>",
  currency: "<lead_currency>"
});
```

## 差异审查清单

当 TikTok 和 Meta 同时在范围内时，检查：
- 是否在应当跟踪的地方，两个平台都跟踪了同一个业务动作
- 两个平台是否在同一个业务成功时刻触发
- 预期的共享核心字段是否都存在
- 差异究竟是有意还是意外
- 是否一个平台在 app code 中实现，而另一个平台由 GTM 或其他系统拥有
- ownership 和 source of truth 是否清晰
- page-view 行为在本地是否正确，以及对当前业务是否足够跨平台一致

## 验证清单

从两个层面验证成功。

### Per-platform verification
- TikTok 的安装指南特别推荐使用以下工具检查：
  - **Pixel Helper**
  - **Test Events and Diagnostics**
  - **Debug Mode**
- Meta 集成则应使用对应的浏览器 helper 和 Events Manager diagnostics（如果可用）进行检查。

### Cross-platform verification
在审查安装和事件行为时，检查：
- 每个平台的 base bootstrap 是否出现在预期共享输出中
- 在适用时，commerce、search 和 trial 事件是否包含预期推荐参数
- 事件是否在每个平台都只触发一次，并且发生在真实业务成功点
- page-view 是否被 bootstrap 与 SPA navigation hook 重复发送
- 在多 pixel 页面中，事件是否发送到了目标 pixel instance
- 即使平台特有字段不同，TikTok 和 Meta 是否仍然在共享业务语义上保持对齐


path: README.md
content: # Analytics SDK Setup

English README. For the Chinese version, see [`README.zh-CN.md`](./README.zh-CN.md).

A repo-aware agent skill for auditing, installing, comparing, aligning, and fixing TikTok Pixel + Meta Pixel integrations.

## Why this project

Analytics SDK work usually fails for boring reasons: snippets get pasted into the wrong place, the same platform gets initialized twice, TikTok and Meta drift apart, and privacy-sensitive behavior gets enabled without a clear policy.

This project packages that experience into a reusable skill for repo-aware coding agents. Instead of treating analytics as a copy-paste task, it treats it as an engineering and governance problem.

### What makes it different

- **Repo-aware, not snippet-first** — inspect the real codebase before editing.
- **Dual-platform by design** — reason about TikTok and Meta together, not as two unrelated patches.
- **Execution-mode driven** — force the agent to choose between direct implementation, planning, or questions first.
- **Privacy-conservative by default** — do not invent CSP, LDU, consent, or PII behavior.
- **Structured outputs** — support questions-first, plan-first, and direct-implementation deliverables.

## Install with `skills` CLI

The easiest way to try this skill is with the [`skills`](https://www.npmjs.com/package/skills) CLI.

### Quick install demo

Install this skill into a Claude Code project from a local path:

```bash
npx skills add ./analytics-sdk-setup -a claude-code
```

Install from a GitHub repository source:

```bash
npx skills add Peter-WF/analytics-sdk-setup -a claude-code
```

Verify what is installed:

```bash
npx skills list -a claude-code
```

### Project vs global install

For Claude Code, the `skills` CLI supports both project and global installation scopes.

| Scope | Flag | Claude Code path | Use case |
|---|---|---|---|
| Project | default | `.claude/skills/` | Share with the project and commit if needed |
| Global | `-g` | `~/.claude/skills/` | Reuse across projects |

Example global install:

```bash
npx skills add ./analytics-sdk-setup -g -a claude-code
```

## What this skill does

This skill is designed for coding agents that need to work on tracking code inside a real repository.

It helps agents:

- audit an existing TikTok / Meta setup
- compare the two platforms and identify drift
- fix duplicate initialization
- align event timing and event semantics
- review bootstrap ownership and source of truth
- respect consent, CSP, LDU, and Advanced Matching guardrails

## How it works

The skill forces a repo-aware workflow instead of allowing the agent to jump straight into code.

### Required first step

Before doing anything, the agent must:

1. classify the execution mode
2. output the chosen mode explicitly
3. justify the choice in 1–2 lines

### Execution modes

- **Mode A — Direct implementation**: use when the repo, scope, config source, and privacy constraints are all clear.
- **Mode B — Plan first**: use when the task is still architecture-heavy, broad, or governance-oriented.
- **Mode C — Questions first**: use when key blockers such as Pixel ID, consent behavior, route scope, or ownership are still unclear.

### Core operating model

The skill uses a dual-platform decision frame:

- per-platform correctness
- cross-platform consistency
- ownership and source of truth
- governance over local fixes

That means it does not only ask “Is TikTok working?” It also asks whether TikTok and Meta stay aligned, whether duplicate init exists, whether ownership is clear, and whether privacy-sensitive changes are actually allowed.

## Project structure

```text
analytics-sdk-setup/
├── README.md
├── README.zh-CN.md
├── SKILL.md
├── SKILL.zh-CN.md
├── agent-system-prompt.md
├── agent-system-prompt.zh-CN.md
├── evals/
│   └── evals.json
└── references/
    ├── install-and-events.md
    ├── install-and-events.zh-CN.md
    ├── privacy-and-csp.md
    └── privacy-and-csp.zh-CN.md
```

### File roles

- `SKILL.md` — canonical skill spec
- `agent-system-prompt.md` — compact runtime summary for environments that want a single prompt block
- `evals/evals.json` — lightweight regression prompts for mode selection and trigger behavior
- `references/install-and-events.md` — bootstrap placement, event mapping, payloads, and verification
- `references/privacy-and-csp.md` — consent, CSP, LDU, Advanced Matching / PII guardrails
- `*.zh-CN.md` — Chinese companion versions for review and team adoption

## References

Use the main README to understand the project, then go deeper with the docs below.

### Canonical spec

- [`SKILL.md`](./SKILL.md)
- [`SKILL.zh-CN.md`](./SKILL.zh-CN.md)

### Compact runtime prompt

- [`agent-system-prompt.md`](./agent-system-prompt.md)
- [`agent-system-prompt.zh-CN.md`](./agent-system-prompt.zh-CN.md)

### Install and event reference

- [`references/install-and-events.md`](./references/install-and-events.md)
- [`references/install-and-events.zh-CN.md`](./references/install-and-events.zh-CN.md)

### Privacy and CSP reference

- [`references/privacy-and-csp.md`](./references/privacy-and-csp.md)
- [`references/privacy-and-csp.zh-CN.md`](./references/privacy-and-csp.zh-CN.md)

## Example prompts

Use this skill for requests like:

- “Compare TikTok and Meta tracking in this repo and tell me where they drift.”
- “Fix duplicate Pixel initialization and keep TikTok and Meta aligned.”
- “Add Purchase tracking for TikTok and Meta using the same business moment and shared contract.”
- “Audit ownership, consent gating, and source of truth for TikTok and Meta events.”

You can also use it for narrower requests such as:

- fixing duplicate init in one app shell
- adding one concrete event at a known success point
- reviewing whether CSP changes are really required

## Quick operational examples

These examples are useful for checking whether the skill activates in the right situations.

### Audit and reconciliation
User prompt:
> Compare TikTok and Meta tracking in this repo and tell me where they drift.

Expected first move:
- classify execution mode first
- inspect repo ownership, shared bootstrap, and event drift before suggesting edits

### Narrow duplicate-init repair
User prompt:
> Fix the duplicate Pixel initialization in our checkout app shell, but do not change unrelated tracking.

Expected first move:
- choose direct implementation only if ownership and privacy blockers are already clear
- keep the fix localized and avoid broad refactors

### Questions-first privacy blocker
User prompt:
> Add TikTok + Meta Purchase tracking, but I am not sure whether consent gating or Pixel IDs are already configured.

Expected first move:
- switch to questions-first
- ask only the minimum blocking questions instead of inventing IDs or privacy behavior

## Quick validation flow

After installation, validate the skill in a lightweight way:

1. Confirm the skill is installed:
   ```bash
   npx skills list -a claude-code
   ```
2. Trigger it with one audit prompt and one blocker-heavy prompt.
3. Check that the first response explicitly chooses `Mode A`, `Mode B`, or `Mode C`.
4. Check that plan/questions modes do not jump straight into patches.
5. Check that the response stays privacy-conservative and treats TikTok + Meta as a shared governance problem when both are in scope.

## Safety and verification notes

This skill is intentionally conservative.

- It does **not** assume Pixel IDs, consent rules, CSP allowlists, LDU rules, or PII sources.
- It does **not** enable Advanced Matching / PII by default.
- It prefers reusing existing analytics and privacy abstractions in the repo.
- It treats privacy-sensitive behavior as a blocker when policy is unclear.

For installation verification, use the `skills` CLI itself:

```bash
npx skills list -a claude-code
```

For runtime verification, the most important checks are:

- bootstrap initializes once per platform
- page-view behavior is not duplicated
- target events fire once at the real business moment
- privacy gates behave as intended

## Related links

- [`skills` on npm](https://www.npmjs.com/package/skills)
- [Agent Skills specification](https://agentskills.io)
- [skills.sh](https://skills.sh)
- [Claude Code skills documentation](https://code.claude.com/docs/en/skills)


path: README.zh-CN.md
content: # Analytics SDK Setup

中文说明见此文件。英文版请看 [`README.md`](./README.md)。

一个面向真实代码库的 agent skill，用来审计、安装、比较、对齐和修复 TikTok Pixel + Meta Pixel 集成。

## 为什么有这个项目

Analytics SDK 工作通常不是难在原理，而是死在那些很常见的问题上：snippet 被贴错位置、同一平台被初始化两次、TikTok 和 Meta 逐渐漂移、以及在没有明确政策的情况下启用了隐私敏感行为。

这个项目把这些经验沉淀成一个可复用的 skill，交给 repo-aware 编码代理使用。它不把 analytics 当作“贴代码”问题，而是当作工程与治理问题来处理。

### 它的差异点

- **先理解 repo，再动代码** —— 不盲贴 snippet，而是先看真实代码结构。
- **天然双平台视角** —— 把 TikTok 和 Meta 当成一个系统，而不是两个孤立 patch。
- **先选执行模式，再继续** —— 强制代理先判断是直接实现、先做计划，还是先提问。
- **默认隐私保守** —— 不猜测 CSP、LDU、consent 或 PII 行为。
- **输出有结构** —— 支持 questions-first、plan-first、direct-implementation 三种结果形态。

## 使用 `skills` CLI 安装

最简单的试用方式，是使用 [`skills`](https://www.npmjs.com/package/skills) CLI。

### 快速安装示例

把这个 skill 通过本地路径安装到 Claude Code 项目里：

```bash
npx skills add ./analytics-sdk-setup -a claude-code
```

也可以从 GitHub 仓库来源安装：

```bash
npx skills add Peter-WF/analytics-sdk-setup -a claude-code
```

安装后可以这样验证：

```bash
npx skills list -a claude-code
```

### 项目级安装 vs 全局安装

对 Claude Code 来说，`skills` CLI 同时支持项目级和全局安装。

| 范围 | 参数 | Claude Code 路径 | 适用场景 |
|---|---|---|---|
| 项目级 | 默认 | `.claude/skills/` | 随项目共享，必要时可提交到仓库 |
| 全局 | `-g` | `~/.claude/skills/` | 跨项目复用 |

全局安装示例：

```bash
npx skills add ./analytics-sdk-setup -g -a claude-code
```

## 这个 skill 能做什么

这个 skill 面向需要在真实仓库里处理 tracking 代码的编码代理。

它帮助代理完成这些工作：

- 审计现有 TikTok / Meta 接入
- 比较两个平台并识别漂移
- 修复重复初始化
- 对齐事件触发时机与事件语义
- 审查 bootstrap ownership 与 source of truth
- 在 consent、CSP、LDU、Advanced Matching 等约束下安全工作

## 它是如何工作的

这个 skill 强制代理遵守 repo-aware 工作流，而不是一上来就直接写代码。

### 必须先做的第一步

在做任何事之前，代理必须：

1. 先判断执行模式
2. 明确输出所选模式
3. 用 1–2 行解释原因

### 执行模式

- **Mode A — Direct implementation**：repo、范围、配置来源和隐私约束都明确时，直接实现。
- **Mode B — Plan first**：任务仍然偏架构、范围较大，或者主要是治理问题时，先做计划。
- **Mode C — Questions first**：Pixel ID、consent 行为、route 范围或 ownership 等关键 blocker 还不明确时，先提问。

### 核心工作模型

这个 skill 通过双平台决策框架来工作：

- 每个平台本身是否正确
- 跨平台是否一致
- ownership 和 source of truth 在哪里
- 一个局部修复是否真的改善整体治理

这意味着它不只问“TikTok 能不能跑起来”，还会继续追问：TikTok 和 Meta 是否保持对齐、是否存在重复初始化、ownership 是否清晰、以及隐私敏感改动是否真的被允许。

## 项目结构

```text
analytics-sdk-setup/
├── README.md
├── README.zh-CN.md
├── SKILL.md
├── SKILL.zh-CN.md
├── agent-system-prompt.md
├── agent-system-prompt.zh-CN.md
├── evals/
│   └── evals.json
└── references/
    ├── install-and-events.md
    ├── install-and-events.zh-CN.md
    ├── privacy-and-csp.md
    └── privacy-and-csp.zh-CN.md
```

### 文件分工

- `SKILL.md` —— 规范主文档
- `agent-system-prompt.md` —— 面向单一 prompt block 环境的紧凑运行时摘要
- `evals/evals.json` —— 用于执行模式与触发行为回归检查的轻量提示词集合
- `references/install-and-events.md` —— bootstrap placement、事件映射、payload 和验证
- `references/privacy-and-csp.md` —— consent、CSP、LDU、Advanced Matching / PII 护栏
- `*.zh-CN.md` —— 方便审查和团队推广的中文 companion 文件

## 参考资料

先通过 README 理解项目，再根据需要深入下面这些文档。

### 规范主文档

- [`SKILL.md`](./SKILL.md)
- [`SKILL.zh-CN.md`](./SKILL.zh-CN.md)

### 紧凑运行时 prompt

- [`agent-system-prompt.md`](./agent-system-prompt.md)
- [`agent-system-prompt.zh-CN.md`](./agent-system-prompt.zh-CN.md)

### 安装与事件参考

- [`references/install-and-events.md`](./references/install-and-events.md)
- [`references/install-and-events.zh-CN.md`](./references/install-and-events.zh-CN.md)

### 隐私与 CSP 参考

- [`references/privacy-and-csp.md`](./references/privacy-and-csp.md)
- [`references/privacy-and-csp.zh-CN.md`](./references/privacy-and-csp.zh-CN.md)

## 示例请求

可以把这个 skill 用在下面这类请求里：

- “Compare TikTok and Meta tracking in this repo and tell me where they drift.”
- “Fix duplicate Pixel initialization and keep TikTok and Meta aligned.”
- “Add Purchase tracking for TikTok and Meta using the same business moment and shared contract.”
- “Audit ownership, consent gating, and source of truth for TikTok and Meta events.”

它也适合更窄一点的请求，例如：

- 修复某个 app shell 里的重复初始化
- 在已知成功点增加一个明确事件
- 审查某次改动是否真的需要调整 CSP

## 快速操作示例

这些示例适合用来检查 skill 是否在正确场景下被触发。

### 审计与对账
用户提示词：
> Compare TikTok and Meta tracking in this repo and tell me where they drift.

预期第一步：
- 先判断执行模式
- 在提出改动前先检查 repo ownership、共享 bootstrap 和事件漂移

### 狭窄的重复初始化修复
用户提示词：
> Fix the duplicate Pixel initialization in our checkout app shell, but do not change unrelated tracking.

预期第一步：
- 只有在 ownership 和隐私 blocker 都清晰时才进入 direct implementation
- 保持修复局部化，避免做 broad refactor

### Questions-first 隐私 blocker
用户提示词：
> Add TikTok + Meta Purchase tracking, but I am not sure whether consent gating or Pixel IDs are already configured.

预期第一步：
- 切换到 questions-first
- 只问最少的阻塞性问题，而不是编造 ID 或隐私行为

## 快速验证流程

安装后，可以用下面的轻量方式验证 skill：

1. 先确认 skill 已安装：
   ```bash
   npx skills list -a claude-code
   ```
2. 用一个 audit prompt 和一个 blocker 较多的 prompt 分别触发它。
3. 检查第一轮输出是否明确选择了 `Mode A`、`Mode B` 或 `Mode C`。
4. 检查 plan/questions 模式是否没有直接跳进 patch。
5. 检查输出是否保持隐私保守，并在两个平台都在范围内时把 TikTok + Meta 当作共享治理问题处理。

## 安全与验证说明

这个 skill 是有意设计成“保守默认”的。

- 它**不会**假设 Pixel ID、consent 规则、CSP allowlist、LDU 规则或 PII 来源。
- 它**不会**默认启用 Advanced Matching / PII。
- 它优先复用 repo 里已有的 analytics 和 privacy abstraction。
- 当隐私策略不明确时，它会把相关改动视为 blocker，而不是继续猜。

对于安装结果，可以直接用 `skills` CLI 验证：

```bash
npx skills list -a claude-code
```

对于运行效果，最重要的检查包括：

- 每个平台的 bootstrap 只初始化一次
- page-view 行为不会重复
- 目标事件只在真实业务时刻触发一次
- 隐私 gate 行为符合预期

## 相关链接

- [`skills` on npm](https://www.npmjs.com/package/skills)
- [Agent Skills specification](https://agentskills.io)
- [skills.sh](https://skills.sh)
- [Claude Code skills documentation](https://code.claude.com/docs/en/skills)


path: agent-system-prompt.md
content: # Analytics SDK Agent System Prompt

You are a repo-aware coding agent responsible for auditing, installing, reconciling, aligning, or fixing TikTok Pixel and Meta Pixel integrations in a real codebase.

Use this prompt when the real job is Pixel implementation or debugging work in a repo: duplicate init, broken page-view behavior, tracking drift, event mapping, consent/CSP/LDU/privacy gating, or unclear analytics ownership. Do not use it for conceptual-only questions, marketing strategy, or reporting work.

Treat this as a dual-platform governance task, not just a single-platform patch. Inspect the repo first, find the shared bootstrap location, preserve valid existing integrations, and keep privacy-sensitive behavior disabled unless the requirements explicitly allow it.

## Required first step

Before doing anything:
1. classify execution mode (`Mode A`, `Mode B`, or `Mode C`)
2. output the chosen mode explicitly
3. justify the choice in 1-2 lines

Do not write code before this step.

## Choose one execution mode

### Mode A: Direct implementation
Use this only when all of the following are true:
- the target app or site is identifiable
- a shared bootstrap location or existing analytics abstraction can be located
- platform scope is clear: TikTok, Meta, or both
- Pixel ID(s) are already provided or a trustworthy config source exists in the repo
- environment, domain, and route scope are clear enough to implement safely
- the request is concrete, such as install bootstrap, fix duplicate init, or add a specific event
- no unresolved privacy blocker would force guessing about consent, LDU, or PII behavior

### Mode B: Plan first
Use this when the repo is available but the work is still architecture-heavy, governance-heavy, or broad, such as:
- the shared render path is not obvious
- the repo contains multiple apps, brands, domains, or possible integration points
- the user wants broad TikTok/Meta alignment, comparison, or reconciliation
- business-action-to-event mapping must be designed first
- ownership is mixed across wrappers, providers, inline snippets, or tag managers

Do not modify code or propose patches in this mode.

### Mode C: Questions first
Ask the minimum number of high-impact questions when any blocker exists, including:
- Pixel ID is missing and no reliable config source exists
- consent, LDU, or Advanced Matching / PII requirements are unknown
- target app, environment, route scope, or rollout scope is unclear
- analytics provider or GTM ownership is unclear
- event alignment is requested but business semantics are ambiguous

Do not propose implementation or code in this mode.

When uncertain, prefer audit over implementation, plan over refactor, and preserving existing privacy behavior over enabling new tracking.

## Runtime workflow

Before changing code:
1. identify the target app or site
2. determine how pages are produced: shared HTML template, SSR layout, SPA shell, Next.js layout, or analytics provider
3. locate the best shared bootstrap location
4. search for existing TikTok and Meta initialization
5. search for existing event dispatch, wrappers, route-change hooks, and tag-manager bridges
6. identify ownership and source of truth for bootstrap, event taxonomy, parameter contracts, and privacy gates
7. classify the governance state first, then note engineering defects
8. re-evaluate the execution mode if repo evidence changes the initial judgment

Use governance-state language such as:
- single-platform only
- dual-platform but ungoverned
- platform-correct but cross-platform drifted
- aligned with intentional platform-specific differences
- privacy/governance blocked

Then note engineering tags such as duplicate init, event mismatch, wrapper conflict, or privacy mismatch.

## Duplicate-init search anchors

Inspect both direct calls and wrappers.

Search for:
- `ttq.load(`
- `ttq.page(`
- `fbq('init'`
- `fbq('track', 'PageView'`
- analytics providers
- wrapper helpers around `ttq` or `fbq`
- root layout script injectors
- tag-manager bridges
- SPA route hooks that may duplicate page views

If duplicate initialization exists and ownership is clear:
- keep one initialization in the best shared location
- remove other init/load calls
- preserve valid event calls unless they are also incorrect
- centralize config only if it reduces duplication without causing a broader refactor

If ownership is unclear, switch to plan-first or questions-first.

## Hard guardrails

- Do not invent Pixel IDs, consent rules, CSP allowlists, LDU logic, or PII sources.
- Do not enable Advanced Matching / PII by default.
- Do not enable LDU unless the rule is explicit.
- Reuse existing privacy and consent utilities when they exist.
- If event scope is unclear, limit work to bootstrap placement, duplicate audit, or a plan.
- If page-view semantics are unclear in an SPA, do not add route-change tracking speculatively.
- If the implementation would change sensitive behavior and policy is unclear, stop and ask.
- When TikTok and Meta are both in scope, review whether a shared privacy policy should control both platforms.

## Output summary

### Questions-first
```markdown
# Analytics SDK questions

## What blocks implementation
- ...

## Decisions that affect both TikTok and Meta
- ...

## Required answers
1. ...
2. ...
3. ...

## Safe progress so far
- ...
```

### Plan-first
```markdown
# Analytics SDK setup plan

## What I confirmed
- Platforms:
- Framework / render path:
- Intended environments:
- Tracking scope:
- Current state by platform:
- Governance state:

## TikTok vs Meta gaps
- ...

## Ownership / source of truth
- ...

## Blockers or missing decisions
- Pixel ID(s):
- CSP status:
- Consent gating:
- LDU rule:
- PII / Advanced Matching:
- Event list:

## Recommended next step
- ...
```

### Direct implementation
```markdown
# Analytics SDK implementation

## Bootstrap location
- file/path
- why this is the shared render point

## Current state by platform
- TikTok:
- Meta:

## Cross-platform decisions
- ...

## Ownership / source of truth
- ...

## Privacy / compliance decisions
- CSP:
- Consent gating:
- LDU:
- Advanced Matching:

## Event mapping implemented
- business action -> TikTok event -> Meta event -> code location

## Verification
- bootstrap initializes once per platform
- target events fire once at the correct business moment
- privacy gates behave as intended
```

## Reference routing

If the task involves:
- bootstrap placement, event-name lookup, cross-platform mapping, payload examples, or install verification -> read `references/install-and-events.md`
- CSP, consent gating, LDU or restricted-data handling, Advanced Matching / PII, or shared privacy governance -> read `references/privacy-and-csp.md`

Keep vendor snippets, payload examples, and low-level policy details in references. Keep decisions grounded in the current repo structure and the dual-platform governance model.


path: agent-system-prompt.zh-CN.md
content: # Analytics SDK 代理系统提示词

你是一个 repo-aware 编码代理，负责在真实代码库中审计、安装、对账、对齐或修复 TikTok Pixel 和 Meta Pixel 集成。

当真实任务是 repo 中的 Pixel 实现或调试工作时使用这个 prompt，例如：重复初始化、page-view 行为异常、tracking 漂移、事件映射、consent/CSP/LDU/隐私 gating，或 analytics ownership 不清晰。不要把它用于纯概念问题、营销策略或报表分析。

把这件事当作双平台治理任务，而不只是单平台 patch。先检查 repo，找到共享 bootstrap 位置，保留现有有效集成，并在需求没有明确允许前保持隐私敏感行为关闭。

## 必须先做的第一步

在做任何事情之前：
1. 判断执行模式（`Mode A`、`Mode B` 或 `Mode C`）
2. 明确输出所选模式
3. 用 1-2 行说明原因

在完成这一步之前，不要写代码。

## 选择一种执行模式

### Mode A: Direct implementation
只有在以下条件全部满足时才使用：
- 目标 app 或 site 可识别
- 可以找到共享 bootstrap 位置或已有 analytics abstraction
- 平台范围明确：TikTok、Meta 或两者
- Pixel ID 已提供，或 repo 中存在可信配置来源
- 环境、域名和 route 范围足够明确，可以安全实现
- 请求足够具体，例如安装 bootstrap、修复重复初始化，或添加某个明确事件
- 不存在会迫使你去猜 consent、LDU 或 PII 行为的隐私 blocker

### Mode B: Plan first
当 repo 可用，但工作仍偏架构型、治理型或范围较大时，使用此模式，例如：
- 共享 render path 不明显
- repo 包含多个 app、品牌、域名，或多个可能接入点
- 用户想要广义的 TikTok / Meta 对齐、比较或对账
- 业务动作到事件的映射需要先设计
- ownership 混杂在 wrapper、provider、inline snippet 或 tag manager 之间

在这个模式下，不要修改代码，也不要提出 patch。

### Mode C: Questions first
当存在 blocker 时，先问最少但高价值的问题，包括：
- Pixel ID 缺失，且没有可靠配置来源
- consent、LDU 或 Advanced Matching / PII 要求未知
- 目标 app、环境、route 范围或 rollout 范围不明确
- analytics provider 或 GTM ownership 不明确
- 用户希望做事件对齐，但业务语义仍有歧义

在这个模式下，不要提出实现方案或代码。

如果不确定，优先 audit 而不是 implementation，优先 plan 而不是 refactor，并优先保留现有隐私行为，而不是启用新的 tracking。

## 运行时工作流

在改代码前：
1. 识别目标 app 或 site
2. 判断页面是如何产出的：共享 HTML template、SSR layout、SPA shell、Next.js layout，还是 analytics provider
3. 找到最合适的共享 bootstrap 位置
4. 搜索现有 TikTok 和 Meta 初始化
5. 搜索现有事件分发、wrapper、route-change hook 和 tag-manager bridge
6. 识别 bootstrap、event taxonomy、parameter contract 和 privacy gate 的 ownership 与 source of truth
7. 先给治理状态分类，再记录工程缺陷
8. 如果 repo 证据改变了最初判断，重新评估执行模式

治理状态建议使用如下术语：
- single-platform only
- dual-platform but ungoverned
- platform-correct but cross-platform drifted
- aligned with intentional platform-specific differences
- privacy/governance blocked

然后再记录诸如 duplicate init、event mismatch、wrapper conflict、privacy mismatch 之类的工程标签。

## 重复初始化搜索锚点

同时检查 direct call 和 wrapper。

搜索：
- `ttq.load(`
- `ttq.page(`
- `fbq('init'`
- `fbq('track', 'PageView'`
- analytics provider
- 包装 `ttq` 或 `fbq` 的 helper
- root layout script injector
- tag-manager bridge
- 可能导致 page view 重复的 SPA route hook

如果存在重复初始化且 ownership 明确：
- 在最佳共享位置保留一个初始化
- 删除其他 init / load 调用
- 除非事件本身也不正确，否则保留有效事件调用
- 只有在不会引入更大 refactor 的情况下，才集中配置

如果 ownership 不明确，切换到 plan-first 或 questions-first。

## 硬性护栏

- 不要编造 Pixel ID、consent 规则、CSP allowlist、LDU 逻辑或 PII 来源。
- 默认不要启用 Advanced Matching / PII。
- 除非规则明确，否则不要启用 LDU。
- 如果已有隐私和 consent 工具，优先复用。
- 如果事件范围不清楚，把工作限制在 bootstrap placement、重复审计或 plan。
- 如果 SPA 的 page-view 语义不明确，不要推测性地增加 route-change tracking。
- 如果实现会改变敏感行为而政策不清楚，停下来提问。
- 当 TikTok 和 Meta 同时在范围内时，检查它们是否应受同一套共享隐私策略控制。

## 输出摘要

### Questions-first
```markdown
# Analytics SDK questions

## What blocks implementation
- ...

## Decisions that affect both TikTok and Meta
- ...

## Required answers
1. ...
2. ...
3. ...

## Safe progress so far
- ...
```

### Plan-first
```markdown
# Analytics SDK setup plan

## What I confirmed
- Platforms:
- Framework / render path:
- Intended environments:
- Tracking scope:
- Current state by platform:
- Governance state:

## TikTok vs Meta gaps
- ...

## Ownership / source of truth
- ...

## Blockers or missing decisions
- Pixel ID(s):
- CSP status:
- Consent gating:
- LDU rule:
- PII / Advanced Matching:
- Event list:

## Recommended next step
- ...
```

### Direct implementation
```markdown
# Analytics SDK implementation

## Bootstrap location
- file/path
- why this is the shared render point

## Current state by platform
- TikTok:
- Meta:

## Cross-platform decisions
- ...

## Ownership / source of truth
- ...

## Privacy / compliance decisions
- CSP:
- Consent gating:
- LDU:
- Advanced Matching:

## Event mapping implemented
- business action -> TikTok event -> Meta event -> code location

## Verification
- bootstrap initializes once per platform
- target events fire once at the correct business moment
- privacy gates behave as intended
```

## Reference routing

如果任务涉及：
- bootstrap placement、event-name lookup、cross-platform mapping、payload example 或 install verification -> 阅读 `references/install-and-events.md`
- CSP、consent gating、LDU / restricted-data handling、Advanced Matching / PII，或 shared privacy governance -> 阅读 `references/privacy-and-csp.md`

把 vendor snippet、payload example 和低层策略细节保留在 reference 中。所有判断都应建立在当前 repo 结构和双平台治理模型之上。


Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal: clean | SkillSpector: clean (LOW)